Creating a density heatmap plot with Plotly Express in Python

Plotly Express is a Python library that allows us to create line plots quickly and easily, with customizable parameters and an interactive interface.

A density heatmap plot is a visualization technique used to represent the distribution of data points in a two-dimensional space. To create a density heatmap plot using Plotly Express, we need a dataset with two numeric variables representing the X and Y coordinates of the data points.

Features of the density heatmap plot

Some of the key features of a density heatmap plot include:

  • Interactive visualization: Plotly Express creates interactive plots that allow users to zoom, pan, and hover over data points to view their values and customize the display by toggling various plot elements. This interactivity provides a dynamic exploration experience.

  • Density estimation: Plotly Express uses kernel density estimation (KDE) to estimate the density of data points in each plot region. This estimation is used to generate the heatmap, where more intense colors represent areas of higher density.

  • Color mapping: The color mapping of the heatmap can be customized using the color_continuous_scale parameter. Plotly Express provides a range of built-in color scales, such as "Viridis," "Cividis," "Jet," and many more. Users can also define their custom color scales.

  • Binning control: The number of bins on the x and y axes can be adjusted using the nbinsx and nbinsy parameters, respectively. This allows us to control the granularity of the density estimation. Fine-tuning the bin size can help reveal subtle patterns in the data.

  • Marginal histograms: Plotly Express supports the addition of marginal histograms to the density heatmap plot using the marginal_x or marginal_y parameters. These histograms provide additional insights into the distribution of data along each axis.

  • Smoothness control: The smoothness of the density estimation can be adjusted using the histfunc parameter. By default, it is set to "count," but we can change it to "sum," "avg," "min," "max," or any other aggregating function to alter the smoothness of the density estimation.

  • Data aggregation: Plotly Express can display aggregation values within each bin beside the density heatmap. This can be achieved by specifying an aggregation function using the z parameter. For example, we can display the average or sum of a third variable within each bin.

  • Labels and titles: Plotly Express allows us to add labels and titles to the plot to provide context and improve readability. We can customize the axis labels, title, color bar title, and color bar tick labels.

Syntax

The density_heatmap function syntax typically follows this structure:

import plotly.express as px
fig = px.density_heatmap(data_frame, x=x_column, y=y_column, parameters...)
Syntax of the density_heatmap function

Parameters

When creating a density heatmap plot using Plotly Express, we can customize the plot by specifying various parameters. Here are some commonly used parameters:

  • data_frame: The input data frame or a tidy long-form DataFrame containing the data to be plotted.

  • x: The column name or key representing the x-axis values in the data frame.

  • y: The column name or key representing the y-axis values in the data frame.

  • nbinsx: The number of bins to use for the x-axis. Higher values result in finer-grained density estimation.

  • nbinsy: The number of bins to use for the y-axis. Similar to nbinsx, higher values provide finer grained density estimation.

  • color_continuous_scale: The color scale to use for the heatmap. Plotly Express provides various built-in color scales, such as "Viridis," "Cividis," "Jet," and more. We can also define our custom color scales.

  • marginal_x: Determines whether to display a marginal histogram on the x-axis. By default, it is set to False. Set it to True to enable the marginal histogram on x-axis.

  • marginal_y: Determines whether to display a marginal histogram on the y-axis. By default, it is set to False. Set it to True to enable the marginal histogram on y-axis.

  • histfunc: Specifies the aggregation function to use for the density estimation. By default, it is set to "count." We can choose other aggregating functions like "sum," "avg," "min," "max," etc., to adjust the smoothness of the density estimation.

  • z: An additional column name or key representing a third variable to be aggregated and displayed within each bin of the density heatmap.

  • labels: A dictionary specifying custom labels for the x and y axis and color bar. For example, labels=dict(x="Custom X Label", y="Custom Y Label", color="Custom Color Label").

  • title: The title of the density heatmap plot.

  • colorbar_title: The title for the color bar.

  • width and height: The width and height of the plot in pixels.

Return type

The px.density_heatmap() function returns a Plotly figure object that can be displayed with fig.show(). The figure object contains all the information required to produce the line plot, including the data, layout, and style.

Implementation

In the following playground, we create a density heatmap plot using a sample dataset called "tips" provided by Plotly Express. Used attributes (total_bill, and tip) defined as follows:

  • total_bill: This attribute represents the total bill amount for a given meal, including the cost of food, drinks, taxes, and any additional charges. It is a continuous numeric variable representing monetary values.

  • tip: This attribute represents the amount of tip given by the customer for a particular meal. It is also a continuous numeric variable representing monetary values.

cd /usercode && python3 main.py
python3 -m http.server 5000 > /dev/null 2>&1 &
Create a density heatmap plot of tips dataset

Explanation

The code above is explained in detail below:

  • Lines 2–3: import the required libraries for the code: plotly.express as px for creating the density heatmap plot, and pandas as pd for handling data in a DataFrame.

  • Line 6: Loads a sample dataset called tips using the px.data.tips() function provided by Plotly Express. The dataset contains information about restaurant tips.

  • Line 9: Prints the first five rows of the loaded dataset. The head() function retrieves the top rows of the DataFrame and print() displays the result in the console. It helps to inspect the data and verify its structure quickly.

  • Line 12: We use the px.density_heatmap() function to create a density heatmap plot. We pass the DataFrame df as the data source and specify the columns total_bill for the x-axis and tip for the y-axis. The resulting plot is stored in a figure object named fig.

  • Line 15: Customizes the plot by updating its layout using the update_layout() method of the fig Figure object. Here, we set the title of the plot as Density Heatmap Plot and label the x-axis as Total Bill and the y-axis as Tip.

  • Line 22: Display the plot using the fig.show() method, which shows the interactive plot.

Conclusion

The density heatmap plot in Plotly Express is a powerful tool for visualizing the density distribution of data in a 2D space. It allows us to examine concentration, variation, and patterns in data points across regions. We can create insightful density heatmaps with minimal code, customize parameters, and better understand data distribution. This Plotly Express feature is valuable for data exploration, analysis, and presentation, especially with large datasets and spatial patterns.

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

HowDev By Educative. Copyright ©2025 Educative, Inc. All rights reserved