ANALYSIS TOOL BOX

Visualizations

PlotHeatmap

Generate a formatted heatmap to visualize three-dimensional categorical data.

visualizationchartsplottinggraphs

Introduction

A metric that varies across two categorical dimensions at once — infection rate by region and month, ward occupancy by shift — is hard to scan as a table but immediate as a grid of color. PlotHeatmap pivots a long-form DataFrame into exactly that grid, encoding the numeric value as cell color with configurable color scales, discrete buckets, and inline data labels, so patterns across both dimensions jump out visually.

Teaching Note

Heatmaps are essential for:

  • Epidemiology: Visualizing disease incidence rates across geographic regions and time periods.
  • Healthcare: Monitoring patient volume across different hospital wards and work shifts.
  • Data Science: Evaluating model performance metrics across different hyperparameter combinations.
  • Public Health: Monitoring average pollutant levels across urban districts and seasons.
  • Finance: Visualizing the performance of different asset classes across market environments.
  • Marketing: Analyzing customer engagement levels across various campaigns and segments.
  • Operations: Monitoring production efficiency across several manufacturing lines and phases.

Parameters

ParameterTypeDefaultDescription
dataframerequiredpd.DataFrameThe pandas DataFrame containing the categorical and numeric data in long format.
x_axis_column_namerequiredstrThe name of the column to be used for the horizontal axis categories.
y_axis_column_namerequiredstrThe name of the column to be used for the vertical axis categories.
value_column_namerequiredstrThe name of the column containing the numeric values to be color-encoded.
color_palettestr or list'RdYlGn'The seaborn/matplotlib color map or list of colors. Defaults to 'RdYlGn'.
color_map_transparencyfloat0.8The transparency level (alpha) of the heatmap cells. Defaults to 0.8.
color_map_bucketsint7The number of discrete color levels for the heatmap scale. Defaults to 7.
color_map_minimum_valuefloatNoneThe absolute minimum value for the color scale. If None, it is inferred from the data. Defaults to None.
color_map_maximum_valuefloatNoneThe absolute maximum value for the color scale. If None, it is inferred from the data. Defaults to None.
color_map_center_valuefloatNoneThe value representing the center of the color scale (useful for diverging colormaps). If None, the median is used. Defaults to None.
show_legendboolFalseWhether to display the color bar legend mapping values to colors. Defaults to False.
figure_sizetuple(8, 6)The dimensions of the output figure as a (width, height) tuple in inches. Defaults to (8, 6).
border_line_widthint6The width of the lines separating individual heatmap cells. Defaults to 6.
border_line_colorstr'#ffffff'The hex color code for the cell border lines. Defaults to '#ffffff'.
square_cellsboolFalseWhether to force each heatmap cell to be perfectly square. Defaults to False.
show_data_labelsboolTrueWhether to display numeric text labels inside each heatmap cell. Defaults to True.
data_label_fontweightstr'normal'The font weight for the internal cell labels (e.g., 'bold', 'normal'). Defaults to 'normal'.
data_label_colorstr'#262626'The hex color code for the internal cell labels. Defaults to '#262626'.
data_label_fontsizeint12The font size for the internal cell labels. Defaults to 12.
title_for_plotstrNoneThe primary title text at the top of the figure. Defaults to None.
subtitle_for_plotstrNoneDescriptive subtitle text below the main title. Defaults to None.
caption_for_plotstrNoneExplanatory text or notes at the bottom of the plot. Defaults to None.
data_source_for_plotstrNoneText identifying the data source, appended to the caption. Defaults to None.
title_y_indentfloat1.15Vertical offset for the title position relative to the grid. Defaults to 1.15.
subtitle_y_indentfloat1.1Vertical offset for the subtitle position relative to the grid. Defaults to 1.1.
caption_y_indentfloat-0.17Vertical offset for the caption position relative to the grid. Defaults to -0.17.
filepath_to_save_plotstrNoneThe local path (ending in .png or .jpg) where the plot should be exported. If None, the file is not saved. Defaults to None.

Returns

None — the function displays the heatmap using matplotlib and optionally saves it to disk.

Example

python
from analysistoolbox.visualizations import PlotHeatmap
import pandas as pd

# Epidemiology: infection rates by region and month
epi_df = pd.DataFrame({
    'Region': ['North', 'North', 'South', 'South'],
    'Month': ['Jan', 'Feb', 'Jan', 'Feb'],
    'Rate': [12.5, 14.2, 8.5, 9.1]
})
PlotHeatmap(
    epi_df, 'Month', 'Region', 'Rate',
    title_for_plot="Regional Infection Velocity",
    color_palette="YlOrRd"
)