Python:Plotly .Histogram2dContour()

MamtaWardhani's avatar
Published Dec 18, 2024Updated Mar 21, 2025
Contribute to Docs

The .Histogram2dContour() method in Plotly’s graph_objects module creates a 2D histogram with contour lines to visualize the joint distribution of two variables. It uses a grid where color intensity represents the count or aggregated values within each cell, while the contour lines indicate regions of equal density. This method helps visualize relationships and density in bivariate data, helping to uncover patterns and trends.

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

plotly.graph_objects.Histogram2dContour(x=None, y=None, nbinsx=None, nbinsy=None, colorscale=None, contours=None, ...)
  • x: Input data for the x-axis.
  • y: Input data for the y-axis.
  • nbinsx (Optional): The number of bins (intervals) used to divide the x-axis range. If not specified (None), Plotly automatically calculates an appropriate number of bins based on the data.
  • nbinsy (Optional): The number of bins (intervals) used to divide the y-axis range on the data.
  • colorscale (Optional): Defines the color scale for heatmap.
  • contours (Optional): Configuration for contour lines (e.g., levels, start, end, size).

Note: The ellipsis in the syntax (…) indicates additional optional parameters for further customization.

Example

The following example showcases the use of the .Histogram2dContour():

import plotly.graph_objects as go
# Sample data
x = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
y = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# Create the histogram with contours
fig = go.Figure(
go.Histogram2dContour(
x=x,
y=y,
nbinsx=5,
nbinsy=5,
colorscale='Viridis',
contours=dict(start=0, end=4, size=1)
)
)
# Show the figure
fig.show()

The example demonstrates how to use .Histogram2dContour() to create a two-dimensional histogram that includes contour lines which are used to visualize the joint distribution between two variables.

The above code generates the following output:

Histogram2dContour in Plotly

All contributors

Contribute to Docs

Learn Python:Plotly on Codecademy

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours