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 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.
The Histogram
plot syntax typically follows this structure:
import plotly.graph_objects as go# Create a histogram tracehistogram_trace = go.Histogram(x=data, # Your 1D data arrayxbins=dict(start=min(data), end=max(data), size=1), # Optional: Customize bin sizemarker=dict(color='blue'), # Optional: Customize the bar coloropacity=0.7, # Optional: Adjust the opacity of the barsname='Histogram', # Optional: Trace name for legendhoverinfo='x+y', # Optional: Hover information to displayxaxis='x1', # Optional: Associate with a specific x-axisyaxis='y1' # Optional: Associate with a specific y-axis)
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).
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.
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 &
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.
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 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