How to create a heatmap plot with Plotly Graph Objects in Python

Plotly Graph Objects is a Python library that provides a flexible and powerful way to create interactive data visualizations. It is part of the larger Plotly ecosystem, which includes Plotly Express and Plotly.py. Plotly Graph Objects allows us to create and customize various types of charts, plots, and graphs with full control over the visual aspects and interactivity.

Features of the heatmap plot in Plotly Graph Objects

The following are some key features of heatmap plots using Plotly Graph Objects:

Data input: Heatmap plots typically require a 2D array or a data frame where each cell represents a value that will be color-coded.

Color scale: We can choose a color scale to map values to colors. Plotly provides a variety of predefined color scales, and you can also define custom color scales.

Annotations: We can add text annotations to individual cells, which can be useful for displaying the exact values associated with each cell.

Axes labels: Heatmap plots often have labeled axes for rows and columns, which makes understanding the represented data easier.

Title: We can add a title to our heatmap plot to provide context or to clarify what the plot is illustrating.

Color bar: A color bar can be added to the plot to show the correspondence between colors and values. This is particularly useful when conveying the data's numeric meaning.

Customization of colors: We can customize the colors used in the heatmap, including specifying the color for missing or out-of-range values.

Row and column order: We can control the order of rows and columns, which can be important when you want to emphasize certain patterns in the data.

Scaling: We can scale the color mapping based on various criteria, such as row-wise, column-wise, or globally, which can help highlight different aspects of the data.

Hover text: We can include hover text that appears when you hover over individual cells, providing additional information or context.

Z-score normalization: We can normalize the values in the heatmap using Z-score normalization to standardize data and highlight relative differences.

Subplots: We can include multiple heatmaps in a single subplot, easily comparing related datasets.

Syntax

The Heatmap plot syntax typically follows this structure:

import plotly.graph_objects as go
heatmap_trace = go.Heatmap(
z=data, # Your 2D data matrix
colorscale='Viridis', # Choose a color scale
x=['Column 1', 'Column 2', 'Column 3'], # Optional: Labels for the x-axis
y=['Row 1', 'Row 2', 'Row 3'], # Optional: Labels for the y-axis
colorbar=dict(title='Colorbar Title'), # Optional: Customize the colorbar
hoverongaps=False # Optional: Display gaps as blank or not
)
Syntax of the heatmap plot

Parameters

The following are the key parameters for creating a heatmap plot using Plotly Graph Objects:

  • z: This parameter is required, and it represents the 2D data matrix we want to visualize as a heatmap. It should be a list of lists (or a 2D numpy array) where each element represents a cell's value.

  • x (optional): This is an array or list specifying the labels for the columns of the heatmap. It helps in providing context to the data on the x-axis.

  • y (optional): This is an array or list specifying the labels for the heatmap rows. It helps in providing context to the data on the y-axis.

  • colorscale (optional): This specifies the color scale used to map values to colors in the heatmap. Plotly provides a variety of predefined color scales, such as 'Viridis', 'YlOrRd', 'Blues', etc. We can also create custom color scales.

  • colorbar (optional): This allows customization of the color bar corresponding to the heatmap values. You can set properties like the title of the color bar using the colorbar dictionary.

  • zmin and zmax (optional): They set the minimum and maximum values of the color scale. Values below zmin will be mapped to the lowest color, and values above zmax will be mapped to the highest color.

  • hoverongaps (optional): This is a boolean parameter that controls whether gaps (missing values) in the data should be displayed as blank.

  • hoverinfo (optional): This specifies what information appears when you hover over a cell. It can be set to “x+y+z” to display x, y, and z values or customized to show specific information.

  • text (optional): This is an array or list of texts appearing on each cell's hover tooltip. Useful for providing additional information about each cell.

  • transpose (optional): This is a boolean parameter that transposes the heatmap, swapping rows and columns if set to True.

  • reversescale (optional): This is a boolean parameter that reverses the color scale if set to True.

  • showscale (optional): This is a boolean parameter to control whether or not the color scale is displayed.

  • colorbar_tickprefix (optional): This is a string that specifies a prefix for color bar tick labels.

  • colorbar_ticksuffix (optional): This is a string that specifies a suffix for color bar tick labels.

  • colorbar_tickmode (optional): This specifies the mode of color bar tick generation. It can be set to 'auto', 'array', or `linear'.

  • colorbar_tickvals (optional): This is an array of tick values for the color bar. We use this parameter to set specific tick values manually.

  • colorbar_ticktext (optional): This is an array of tick text labels for the color bar. We use this parameter to specify custom tick labels.

Return type

When we create a visualization like a heatmap plot using the go.Heatmap trace and the go.Figure constructor, we are essentially creating a figure object that represents our plot. The figure object contains all the necessary information about our plot, including the data, traces, layout, and any additional settings or customizations we've applied.

Implementation

In the following playground, we create a heatmap plot using a sample dataset called “iris” provided by Plotly Express. Attributes of the “iris” dataset are (sepal_width, sepal_length, petal_width, petal_length and species) defined as follows:

sepal_length: The length of the iris flower's sepal (the outermost whorl of a flower), measured in centimeters.

sepal_width: The width of the iris flower's sepal, measured in centimeters.

petal_length: The length of the iris flower's petal (the innermost whorl of a flower), measured in centimeters.

petal_width: The width of the iris flower's petal, measured in centimeters.

species: The categorical label representing the species of the iris flower, including “setosa,” “versicolor,” and “virginica.”

cd /usercode && python3 main.py
python3 -m http.server 5000 > /dev/null 2>&1 &
Visualizing Iris dataset correlations with a heatmap in Plotly Graph Objects

Code explanation

The code above is explained in detail below:

  • Lines 1–3: Imports the necessary modules: plotly.graph_objects for creating custom plots, plotly.express for simplified plotting, and pandas for data manipulation.

  • Line 6: Loads the Iris dataset using Plotly Express's built-in sample dataset.

  • Line 9: Prints the first five rows of the loaded dataset using the head() method to inspect the data.

  • Lines 12–19: Creates a heatmap trace using Plotly Graph Objects (go.Heatmap). Let's break down its components:

    • z=df.corr(numeric_only=True): Sets the z parameter of the heatmap trace to the correlation matrix of the DataFrame df. It calculates the pairwise correlation between the numeric columns in the DataFrame.

    • x=df.columns and y=df.columns: Set the labels for the x and y axes of the heatmap to the column names of the data frame. This effectively uses the column names of the "Iris" dataset as labels.

    • colorscale='Blues': Specifies the color scale for the heatmap. In this case, it's set to 'Blues'.

    • zmin=-1 and zmax=1: Set the minimum and maximum values of the color scale, ensuring that the colors represent correlations between -1 and 1.

  • Line 22: Creates a figure using the go.Figure() constructor and adds the previously created heatmap plot trace.

  • Line 25: Updates the layout of the figure by setting its title.

  • Line 28: Displays the finalized heatmap plot figure using the show() method.

Conclusion

Heatmap plots in Plotly Graph Objects provide a visually intuitive way to explore and analyze data relationships within a 2D matrix. Heatmaps are valuable data visualization and analysis tools with robust customization options, interactivity, and the ability to represent complex patterns using colors. Whether examining correlations, identifying clusters, or highlighting trends, heatmap plots are powerful means to convey insights and patterns within your data, making them a valuable asset for data scientists, analysts, and researchers across various fields.

Unlock your potential: Plotly Graphing and Visualization series, all in one place!

To deepen your understanding of data visualization using Plotly, explore our comprehensive Answer series below:

Plotly express: quick and intuitive visualization

Plotly Graph Objects: Customization and advanced features

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved