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.
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.
The Heatmap
plot syntax typically follows this structure:
import plotly.graph_objects as goheatmap_trace = go.Heatmap(z=data, # Your 2D data matrixcolorscale='Viridis', # Choose a color scalex=['Column 1', 'Column 2', 'Column 3'], # Optional: Labels for the x-axisy=['Row 1', 'Row 2', 'Row 3'], # Optional: Labels for the y-axiscolorbar=dict(title='Colorbar Title'), # Optional: Customize the colorbarhoverongaps=False # Optional: Display gaps as blank or not)
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.
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.
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 &
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.
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 and its methods
Learn the core concepts of Plotly Graph Objects, including its structure, methods, and how to create fully customized visualizations.
Creating a density heatmap plot with Plotly Express in Python
Learn to visualize data density using heatmaps, making patterns in large datasets easy to interpret.
How to create a line plot with Plotly Express in Python
Master the basics of line plots to represent trends over time and relationships between variables.
How to create a bar plot with Plotly Express in Python
Understand how to create bar plots to compare categorical data effectively.
How to create a histogram with Plotly Express in Python
Explore histograms to analyze data distribution and frequency counts efficiently.
How to create a box plot with Plotly Express in Python
Learn to use box plots for statistical visualization, identifying outliers and data spread.
How to create a violin plot with Plotly Express in Python
Combine box plots and KDE plots to compare data distributions effectively.
How to create a 3D line plot with Plotly Express in Python
Extend your data visualization skills by creating 3D line plots for multi-dimensional data representation.
How to create a choropleth map with Plotly Express in Python
Learn how to create geospatial visualizations with choropleth maps for regional data analysis.
Creating parallel coordinates plots with Plotly Express in Python
Visualize multi-dimensional data efficiently with parallel coordinate plots for feature comparison.
How to create a scatter plot on a Mapbox map with Plotly Express
Utilize Mapbox maps to plot scatter data points based on geographic coordinates.
Creating a scatter plot matrix with Plotly Express in Python
Understand relationships between multiple numerical variables using scatter plot matrices.
Plotly Graph Objects: Customization and advanced features
How to create a 3D surface plot with Plotly Graph Objects
Create 3D surface plots for visualizing complex surfaces and mathematical functions.
How to create a box plot with Plotly Graph Objects in Python
Gain full control over box plots, including styling, custom axes, and multiple data series.
How to create a 3D scatter plot with Plotly Express in Python
Visualize high-dimensional data using 3D scatter plots for better insight.
Creating a histogram plot with Plotly Graph Objects in Python
Customize histogram bins, colors, and overlays using Plotly Graph Objects for in-depth analysis.
How to create a bar plot with Plotly Graph Objects in Python
Build highly customizable bar plots, adjusting layout, colors, and interactivity.
How to create a heatmap plot with Plotly Graph Objects in Python
Generate heatmaps with flexible color scales and annotations for better data storytelling.
How to create a pie plot with Plotly Graph Objects in Python
Learn to create pie charts with custom labels, colors, and hover interactions.
Creating a Choropleth plot with Plotly Graph Objects in Python
Explore geospatial visualizations with advanced choropleth maps for regional comparisons.
How to create a violin plot with Plotly Graph Objects in Python
Customize violin plots to represent distribution, density, and probability density functions.
How to create a scatter plot with Plotly Graph Objects in Python
Learn to create scatter plots with detailed hover information, styling, and annotations.
How to create a table with Plotly Graph Objects in Python
Build interactive tables with styling options for presenting structured data.
How to create a bubble plot with Plotly Graph Objects in Python
Understand how to create bubble plots to visualize three variables in a single chart.
Create a 3D scatter plot with Plotly Graph Objects in Python
Explore multi-dimensional data using customized 3D scatter plots.
Creating a density contour plot with Plotly Express in Python
Learn how to visualize data density using contour plots to detect clusters.
How to create a scatter plot with Plotly Express in Python
Master scatter plots to identify correlations, trends, and patterns in datasets.
Free Resources