# Plotly Heatmaps with px.imshow and go.Heatmap

> Plotly heatmap guide with px.imshow and go.Heatmap: text_auto annotations, color scales and midpoints, aspect="auto", correlation triangles, hover text and cell gaps.

Source: https://www.pythoncharts.com/plotly/plotly-heatmaps/ | Published: 2026-11-27 | Author: Alex Scott | Category: Plotly | Tags: plotly, plotly express, heatmap, imshow, correlation, annotations

Make a heatmap in Plotly by passing a 2D table to `px.imshow(table)`. Rows become the y-axis, columns the x-axis, and the values set the color. Add `text_auto=True` to write the values in the cells and `aspect="auto"` to let the cells stretch to fill the figure.

## Quick Example

Sample bike share rentals by weekday and hour:

```python
import numpy as np
import pandas as pd
import plotly.express as px

rng = np.random.default_rng(75)
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
hours = np.arange(6, 23)

def bump(center, width, height):
    return height * np.exp(-0.5 * ((hours - center) / width) ** 2)

weekday = 12 + bump(8, 1.1, 150) + bump(17.5, 1.4, 175) + bump(12.5, 2.0, 45)
weekend = 8 + bump(14, 3.0, 120)
rentals = pd.DataFrame(
    [rng.poisson(weekday if day not in ("Sat", "Sun") else weekend) for day in days],
    index=days, columns=hours,
)

fig = px.imshow(rentals, aspect="auto", color_continuous_scale="YlGnBu",
                labels=dict(x="Hour of day", y="", color="Rentals"),
                title="Bike rentals by weekday and hour")
fig.update_xaxes(dtick=1)
fig.update_traces(xgap=1, ygap=1)
fig.show()
```

![Plotly heatmap of bike rentals by weekday and hour, with weekday peaks at 8 and 17 to 18 o'clock and a broad weekend afternoon peak](https://www.pythoncharts.com/plotly/plotly-heatmaps/images/plotly-heatmap-quick-example.png)

Weekdays have two sharp peaks, around 8:00 and between 17:00 and 18:00. Weekends have one broad afternoon peak. The code targets Plotly 6.x.

## Prepare the Data as a Table

`px.imshow` wants one value per cell. If your data has one row per observation, build the table with `pivot_table`:

```python
# one row per rental, as it might come from a database
trips = (rentals.rename_axis("day").reset_index()
         .melt("day", var_name="hour", value_name="n"))
trips = trips.loc[trips.index.repeat(trips["n"]), ["day", "hour"]].reset_index(drop=True)

table = pd.crosstab(trips["day"], trips["hour"]).reindex(days)
print(table.shape)    # (7, 17)
```

`pd.crosstab` counts rows. Use `df.pivot_table(index=..., columns=..., values=..., aggfunc="mean")` for averages or sums. Both sort labels alphabetically, so `reindex` to restore weekday order.

## Add Values to the Cells

`text_auto=True` annotates each cell, and Plotly picks dark or light text for contrast. Pass a format string such as `".0f"`, `".1%"` or `".2s"` to control the numbers.

```python
blocks = pd.DataFrame({
    "Morning": rentals[[6, 7, 8, 9, 10]].mean(axis=1),
    "Midday": rentals[[11, 12, 13, 14]].mean(axis=1),
    "Evening": rentals[[15, 16, 17, 18, 19]].mean(axis=1),
    "Night": rentals[[20, 21, 22]].mean(axis=1),
})
fig = px.imshow(blocks, text_auto=".0f", aspect="auto", color_continuous_scale="Purples",
                title="Average rentals per hour by time of day")
fig.update_traces(textfont_size=15)
fig.update_xaxes(side="top", title=None, ticklabelstandoff=6)
fig.update_layout(coloraxis_showscale=False, margin_t=100)
fig.show()
```

![Annotated heatmap of average hourly rentals for each weekday in the morning, midday, evening and night](https://www.pythoncharts.com/plotly/plotly-heatmaps/images/plotly-heatmap-annotated.png)

`side="top"` moves the column labels above the grid, and `coloraxis_showscale=False` hides the color bar when the numbers already say it.

## Choose the Color Scale and Range

| Data | Scale | Settings |
|---|---|---|
| Counts or amounts | Sequential: `"Viridis"`, `"YlGnBu"`, `"Purples"` | `zmin=0` |
| Above and below a reference | Diverging: `"RdBu_r"`, `"BrBG"` | `color_continuous_midpoint=0` |
| Several heatmaps to compare | Any | Same `zmin` and `zmax` |
| A few extreme cells | Any | `zmax` below the maximum |

Add `_r` to a scale name to reverse it. Here each cell is the percent difference from that hour's all-week average, with zero in the middle:

```python
diff = (rentals / rentals.mean() - 1) * 100

fig = px.imshow(diff.round(), aspect="auto", color_continuous_scale="BrBG",
                color_continuous_midpoint=0, title="Difference from the hourly average (%)",
                labels=dict(x="Hour of day", color="%"))
fig.update_xaxes(dtick=1)
fig.show()
```

![Diverging heatmap of percent difference from the hourly average, with weekday commute hours above average and weekend commute hours far below](https://www.pythoncharts.com/plotly/plotly-heatmaps/images/plotly-heatmap-diverging.png)

## Correlation Matrix Heatmap

Fix the range at -1 to 1 so colors mean the same thing across charts. Setting the upper triangle to `NaN` leaves those cells blank.

```python
n = 365
temp = rng.normal(15, 8, n)
rain_mm = rng.gamma(0.6, 4, n)
daily = pd.DataFrame({
    "Temperature": temp,
    "Rain": rain_mm,
    "Humidity": 70 - 0.6 * temp + 1.4 * rain_mm + rng.normal(0, 7, n),
    "Wind": rng.gamma(3, 4, n),
    "Rentals": 900 + 38 * temp - 35 * rain_mm + rng.normal(0, 180, n),
})
corr = daily.corr()
lower = corr.where(np.tril(np.ones(corr.shape, dtype=bool)))

fig = px.imshow(lower, text_auto=".2f", zmin=-1, zmax=1, color_continuous_scale="RdBu_r",
                title="Correlations between daily measurements", width=640, height=540,
                template="plotly_white")
fig.update_xaxes(showgrid=False)
fig.update_yaxes(showgrid=False)
fig.show()
```

![Lower triangle correlation heatmap of temperature, rain, humidity, wind and rentals, with rentals positively correlated with temperature and negatively with rain](https://www.pythoncharts.com/plotly/plotly-heatmaps/images/plotly-heatmap-correlation.png)

Rentals rise with temperature and fall with rain, while wind is close to zero against everything. The default `aspect="equal"` keeps these cells square.

## Customize the Hover Text

`hovertemplate` uses `%{x}`, `%{y}` and `%{z}`. `<extra></extra>` removes the side box.

```python
fig = px.imshow(rentals, aspect="auto", color_continuous_scale="YlGnBu",
                title="Hover for a sentence about each cell")
fig.update_traces(hovertemplate="%{y} at %{x}:00<br><b>%{z} rentals</b><extra></extra>")
fig.show()
```

![Bike rental heatmap using a custom hover template](https://www.pythoncharts.com/plotly/plotly-heatmaps/images/plotly-heatmap-hover.png)

## go.Heatmap for More Control

`go.Heatmap` takes `x`, `y` and `z` separately. Use it for custom cell text, uneven bins, or heatmaps inside [subplots](https://www.pythoncharts.com/plotly/plotly-make-subplots/). Unlike `px.imshow`, it draws the first row at the **bottom**, so reverse the y-axis.

```python
import plotly.graph_objects as go

capacity = 200
share = rentals.loc[days, [7, 8, 9, 16, 17, 18]] / capacity
labels = share.map(lambda v: "full" if v >= 0.9 else f"{v:.0%}")

fig = go.Figure(go.Heatmap(
    z=share.values, x=[f"{h}:00" for h in share.columns], y=share.index.tolist(),
    text=labels.values, texttemplate="%{text}",
    colorscale="OrRd", zmin=0, zmax=1, xgap=3, ygap=3,
    colorbar=dict(title="Capacity", tickformat=".0%"),
))
fig.update_yaxes(autorange="reversed")
fig.update_layout(template="plotly_white", title="Share of dock capacity used at peak hours")
fig.show()
```

![Heatmap of dock capacity used at commute hours with percentage labels and the word full on the busiest weekday cells](https://www.pythoncharts.com/plotly/plotly-heatmaps/images/plotly-heatmap-go.png)

## Common Problems

- **The heatmap is a thin strip.** The default aspect keeps cells square. Pass `aspect="auto"`.
- **Numbers don't appear.** Cells may be too small for the text. Make the figure larger, shorten the format, or drop the annotations.
- **Rows are upside down.** `go.Heatmap` and `px.imshow(..., origin="lower")` start at the bottom.
- **Integer column names spread unevenly.** Numeric columns make a numeric axis. Convert them to strings if the values aren't evenly spaced.

## Plotly vs Seaborn Heatmaps

Use Plotly when readers need to hover over a large grid. For a figure in a paper or report, [Seaborn's `heatmap`](https://www.pythoncharts.com/seaborn/heatmaps-seaborn/) has clustering companions and fine control over annotations. For a calendar layout, see the [GitHub-style contribution heatmap](https://www.pythoncharts.com/python/github-contribution-heatmap-python/).

## Similar Topics

- [Seaborn Heatmaps](https://www.pythoncharts.com/seaborn/heatmaps-seaborn/)
- [Customize Hover Tooltips in Plotly](https://www.pythoncharts.com/plotly/plotly-customize-hover-tooltips/)
- [Plotly Express Bar Charts: Grouped, Stacked, and Labeled](https://www.pythoncharts.com/plotly/plotly-express-bar-charts/)
