Creating a histogram 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 histogram plot in Plotly Graph Objects

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

  • Trace type selection: We can choose the type of histogram we want to create, such as “histogram” for a standard histogram or “histogram2d” for a 2D histogram.

  • Data input: We provide our dataset as the input data. We want to analyze and display this numerical data as a histogram.

  • Binning: We have control over the bin size or binning algorithm. We can specify the number of bins, the bin width, or use an automatic binning method.

  • Normalization: We can choose whether to normalize the histogram, which scales the counts in each bin to represent proportions or probabilities.

  • Colors and styling: We can customize our histogram bar color, opacity, and style to match our visualization preferences.

  • Labels and titles: We can add labels to the x and y-axes and a title to our plot, making it more informative and understandable.

  • Hover information: We can configure hover information to display additional details when we hover over individual bars, such as bin counts or specific data points.

  • Axes configuration: We can customize various aspects of our axis, including their titles, ranges, and scales (linear or logarithmic).

  • Subplots: If we’re creating a subplot layout, we can arrange our histogram plot alongside other plots for comparison and analysis.

  • Annotations: We can annotate our histogram with text or shapes to highlight specific features or points of interest within the distribution.

  • Updating and interactivity: With Plotly, we can create interactive histograms. We can update the plot dynamically in response to user interactions, such as zooming or panning.

  • Themes and templates: We can apply predefined themes or custom templates to ensure our histogram plot matches our data visualization project’s overall look and feel.

Syntax

The Histogram plot syntax typically follows this structure:

import plotly.graph_objects as go
# Create a histogram trace
histogram_trace = go.Histogram(
x=data, # Your 1D data array
xbins=dict(start=min(data), end=max(data), size=1), # Optional: Customize bin size
marker=dict(color='blue'), # Optional: Customize the bar color
opacity=0.7, # Optional: Adjust the opacity of the bars
name='Histogram', # Optional: Trace name for legend
hoverinfo='x+y', # Optional: Hover information to display
xaxis='x1', # Optional: Associate with a specific x-axis
yaxis='y1' # Optional: Associate with a specific y-axis
)
Syntax of the histogram plot

Parameters

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

  • x (required): The data you want to plot as a histogram, provided as a 1D array or list.

  • xbins (optional): A dictionary that allows you to specify how the data should be binned. It can include the following parameters:

    • start: The starting value for binning.

    • end: The ending value for binning.

    • size: The size of each bin.

  • histnorm (optional): Specifies the type of histogram normalization. Options include:

    • ‘count’ (default): Shows the number of data points in each bin.

    • ‘percent’: Shows the percentage of data points in each bin.

    • ‘probability’: Normalizes to form a probability density.

    • ‘density’: Normalizes to form a probability density (same as ‘probability’).

  • histfunc (optional): Specifies the aggregation function used for multiple data points falling into the same bin. Options include:

    • ‘count’ (default): Counts the number of data points in each bin.

    • ‘sum’: Sums the values of data points in each bin.

    • ‘avg’: Calculates the average of data points in each bin.

    • ‘min’: Finds the minimum value in each bin.

    • ‘max’: Finds the maximum value in each bin.

  • marker (optional): A dictionary to customize the appearance of the histogram bars. You can specify attributes like color, opacity, and line (for border color and width).

  • opacity (optional): Sets the opacity of the bars in the histogram (a value between 0 and 1).

  • name (optional): A string that assigns a name to the histogram trace, which is used in legends when multiple traces are plotted.

  • hoverinfo (optional): Determines what information is displayed in the hover tooltip. You can customize it to show different combinations of data using tokens like ‘x’, ‘y’, and ‘name’.

  • xaxis and yaxis (optional): Associates the trace with specific x and y axes. This is useful when working with multiple axes in a subplot.

  • bargap (optional): Specifies the gap (as a fraction of the bar width) between adjacent bars.

  • bargroupgap (optional): Specifies the gap (as a fraction of the bar width) between groups of bars when multiple histograms are plotted together.

  • orientation (optional): Specifies the orientation of the histogram. It can be either ‘v’ (vertical, default) or ‘h’ (horizontal).

Return type

When we create a visualization like a histogram plot using the go.Histogram 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 histogram plot using a sample dataset called “iris” provided by Plotly Express. Attributes of Iris dataset (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 petal width distribution in the iris dataset with Plotly Graph Objects

Code explanation

The code above is explained in detail below:

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

  • Line 6: Load the Iris dataset using Plotly Express built-in sample dataset.

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

  • Lines 12–15: Creates a histogram trace (histogram_trace) using Plotly Graph Objects (go). It specifies that we want to create a histogram of the ‘petal_width’ column from the loaded Iris dataset. The name attribute sets the name for this trace, which is used in legends if you have multiple traces.

  • Line 19: Create a figure using the go.Figure() constructor and add the previously created histogram plot trace.

  • Line 22: Update the layout of the figure by setting its title.

  • Line 25: Display the finalized histogram plot figure using the show() method.

Conclusion

The histogram plot in Plotly Graph Objects provides a powerful and flexible tool for visualizing the distribution of data. With customizable parameters for binning, color, labeling, and layout, users can tailor their histograms to effectively convey insights from their datasets. Whether it’s exploring the spread of data, identifying central tendencies, or detecting outliers, histogram plots offer a clear and intuitive representation of data distributions. Furthermore, Plotly’s interactive capabilities enable users to dive deeper into their data by allowing for zooming, panning, and hover interactions. This feature-rich functionality makes Plotly’s histogram plots a valuable asset for data analysis and visualization, catering to both beginners and advanced users in their quest to understand data patterns and trends.


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