Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 42 ยท Statistical and Scientific Charts

Heatmaps and Contour Plots

Draw heatmaps and contour plots in Plotly: px.imshow for matrices and correlation tables, go.Heatmap, 2D histograms with density_heatmap, contour levels, color scales and annotations.

A heatmap turns a table of numbers into a grid of colored cells. It is the best way to see patterns in a matrix: a correlation table, a calendar of activity, a confusion matrix, a pivot table. A contour plot draws lines (or filled bands) of equal value, like the elevation lines on a map, and shows the shape of a surface z = f(x, y).

Both chart types map a number to a color scale, so choosing the right scale is part of the job: this lesson covers it and the next lesson goes further.

px.imshow: the quick heatmap

px.imshow takes a 2D array or DataFrame and draws it. For a DataFrame, the index becomes the y axis labels and the columns become the x axis labels. This makes it ideal for pivot tables and correlation matrices.

Python A heatmap of a pivot table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that imshow creates a heatmap trace (a true image would use the image type). Two cells are missing (nobody ate lunch on Saturday or Sunday in this data), shown as empty cells, and text_auto=".2f" prints each number with two decimals. aspect="auto" stretches cells to fill the chart instead of forcing squares.

Correlation matrices

A correlation matrix is a heatmap that deserves a diverging color scale centered on zero, so positive and negative correlations get different colors, and zmin=-1, zmax=1 fix the range:

Python A correlation heatmap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Always fix the range for correlations. Without zmin and zmax, the scale adapts to the data, so the color of 0.3 would differ from chart to chart, which misleads readers. The same applies to any set of heatmaps you want to compare.

go.Heatmap: x, y and z

With graph objects you provide the three arrays: z is the 2D grid of values, and x and y label its columns and rows. Here is a heatmap and a contour plot of the same surface, with plotly.js:

Heatmap and filled contour of one surface

The two traces take identical arguments. The heatmap paints one color per cell; the contour plot interpolates between cells and draws the boundaries of equal value. ncontours sets the approximate number of levels, and contours.start, end and size define them exactly. With contours.coloring="lines" you get lines only, with "heatmap" a smooth color fill and with "fill" (default) flat color bands.

Density heatmaps: 2D histograms

When you have thousands of points, a scatter plot turns into a blob. A 2D histogram counts the points in each cell instead, and shows the density as color. px.density_heatmap does this, and px.density_contour draws contour lines of the same density:

Python 2D histogram and density contour

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

histogram2d is the trace type behind density heatmaps: like the 1D histogram, it receives raw points and bins them in the browser. histfunc and z let you aggregate a third variable per cell (mean sales per grid square, for example).

Heatmap tips

  • Pick the scale by the data: sequential (Blues, Viridis) for amounts, diverging (RdBu) for values around a center such as zero or an average.
  • Sort rows and columns meaningfully (alphabetical order hides patterns; clustering reveals them).
  • Annotate cells with text_auto when the grid is small (up to about 15 x 15), so exact numbers are available.
  • Missing cells appear blank; hoverongaps=False prevents hover boxes on them, and xgap / ygap draw thin gaps between cells for a tile look.
  • Large matrices are fine, since plotly.js draws heatmaps efficiently, but labels need tickangle or fewer ticks.
  • Real images: px.imshow(array_with_shape_(h, w, 3)) draws an RGB image. It becomes an image trace and works for pictures, masks and photos.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do the rows and columns of a DataFrame become in px.imshow(df)?

    The index labels the y axis (rows) and the column names label the x axis.
  2. 2. Which settings are appropriate for a correlation heatmap?

    Correlations are centered on zero and bounded by -1 and 1, so fix the range and use a diverging scale.
  3. 3. What is the difference between go.Heatmap and go.Contour with the same x, y, z?

    They take identical inputs and show the same data in different ways.
  4. 4. What does px.density_heatmap do with raw x and y data?

    It is a 2D histogram (histogram2d trace).
  5. 5. What does contours.coloring="lines" do?

    lines draws only lines, fill colors bands and heatmap gives smooth colors.

Summary

  • Heatmaps show a matrix as colored cells; px.imshow builds them from arrays and DataFrames, go.Heatmap from x, y, z.
  • Correlations and other signed values need a diverging scale and a fixed zmin/zmax.
  • Contour plots draw levels of a surface; ncontours, contours.size and coloring shape them.
  • px.density_heatmap and px.density_contour replace overcrowded scatter plots with 2D histograms.

Next: Trendlines and Error Bars