How to create a bar plot with Plotly Graph Objects in Python

Key takeaways:

  • Plotly Graph Objects provides powerful tools for creating highly interactive bar plots that enhance data exploration.

  • Features like hover effects, legends, and zooming make it easy to interact with the data, revealing more insights with minimal effort.

  • Customization features like labels, annotations, and colors allow you to tailor the charts to your specific needs and preferences.

  • Support for stacked and grouped bars enables you to compare datasets visually, whether side by side or as cumulative totals.

  • Error bars and subplots add depth to your analysis by showing data variability and allowing for easy comparison between multiple plots.

  • Export options allow you to share charts in formats like PNG, PDF, or HTML, making it easy to present and distribute your work.

Plotly Graph Objects for interactive bar charts

Plotly Graph Objects is a flexible and powerful Python library for creating interactive data visualizations. It is part of the larger Plotly ecosystem and gives users full control over customizing bar plots and other charts. In this Answer, we’ll explore how to use Plotly Graph Objects to create basic interactive bar charts that you can use as a base to even build advanced customization.

Plotly logo
Plotly logo

Features of the bar plot in Plotly Graph Objects

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

  • Interactivity: Plotly bar charts are interactive, offering hover effects, zooming, panning, and clickable legends.

  • Data labels: This easily adds and customizes labels to display bar values.

  • Custom colors: This sets custom bar colors to distinguish between data categories or series.

  • Annotations: This adds text or shapes (like lines and arrows) to highlight specific points.

  • Multiple traces: This creates grouped or stacked bar charts for comparing datasets.

  • Orientation: This builds horizontal or vertical bars to suit your dataset.

  • Custom hover info: This personalizes tooltips to display custom data on hover.

  • Responsive: Charts are responsive by default, adjusting to fit screens of any size.

  • Exportability: This export charts as images (PNG, JPEG), PDFs, or HTML files.

  • Animations: This brings your bar charts to life with dynamic animations.

In addition to the core features, Plotly bar plots offer several advanced options. You can customize “Legends” for clarity, add “Error Bars” to represent uncertainties, and use “Subplots” to arrange multiple plots in a grid for comparison. “Stacked Bars” help visualize cumulative totals, while “Themes and Styling” enable full control over the chart’s appearance. Plotly also allows for “Custom Hover Information,” and its “Exportability” supports formats like PDFs and HTML, making it ideal for dynamic, shareable visualizations.

Plotly bar plot syntax explained

The Bar plot syntax typically follows this structure:

import plotly.graph_objects as go
bar_plot = go.Figure(go.Bar(
x=['Category A', 'Category B', 'Category C'], # Labels for the x-axis
y=[25, 40, 30], # Values for the y-axis
text=['Value: 25', 'Value: 40', 'Value: 30'], # Text to display on or next to the bars
hoverinfo='x+y' # Information to display on hover
marker=dict(color='blue'), # Customize the color of the bars
name='Bar Plot', # Name for the trace (used in legends)
orientation='v' # Orientation of the bars
))
Syntax of the bar plot

Parameters

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

  • x (required): The data for the x-axis, typically representing the categories or labels for each bar.

  • y (required): The data for the y-axis, representing the values associated with each category.

  • orientation: This specifies the orientation of the bars. Use 'v' for vertical bars (the default orientation) or 'h' for horizontal bars.

  • text: An array or list of text labels to be displayed on or next to the bars.

  • hoverinfo: A string specifying what information is displayed when hovering over a bar. Options include 'x', 'y', 'text', 'name' or combinations of these.

  • marker: Allows you to customize the appearance of the bars, including their color, opacity, and more.

Following are some other parameters that you might find useful:

  • name: A name for the trace, which is used in legends and tooltips.

  • width: Adjusts the width of the bars.

  • base: For stacked bar plots, specify the base for the bars below each one.

  • offset: Shifts the bars by a specified amount.

  • customdata: An array or list of custom data associated with each bar. This data can be used for custom interactions.

  • hovertemplate: Allows you to create a custom tooltip format using text and data from the bar plot.

  • showlegend: Controls whether the trace appears in the legend.

  • opacity: Adjusts the transparency of the bars.

  • insidetextfont and outsidetextfont: Customize the font style of the text labels inside and outside the bars.

  • textposition: Defines the position of the text labels with respect to the bars. Options include 'inside', 'outside', 'auto', 'none', and more.

  • cliponaxis: Determines whether the bars are clipped to the plotting area or not.

  • offsetgroup: Specifies the offset group for bars, useful for grouping bars together.

  • alignmentgroup: Groups bars together for alignment purposes.

  • barnorm: Allows you to normalize bars to a specific total (useful for creating stacked bars with percentages).

  • x0: Sets the x-coordinate at which the bars are centered (useful for creating grouped bars).

Return type

When we create a visualization like a bar plot using the go.Bar 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.

Code example

In the following playground, we create a bar plot using a sample dataset called “iris” provided by Plotly Express. Attributes of Iris dataset are listed 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.”

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd

# Load the iris dataset
df = px.data.iris()

# Display the first five rows of the data
print(df.head())

# Create bar plot
bar_trace = go.Bar(
    x=df.species,
    y=df.petal_length,
    name='Petal'
)

# Create figure and add trace
fig = go.Figure(bar_trace)

# Customize layout
fig.update_layout(title='Bar Plot of Petal Length by Species')

# Display interactive plot
fig.show()
Creating an interactive bar plot of petal length by species 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’s 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–16: We define a bar trace named bar_trace using go.Bar(). This trace will be used to create the bar plot. In the bar_trace definition, we specify that the x-axis (x) should use the species column, and the y-axis (y) should use the petal_length column from the data frame df. We also name this trace as 'Petal'.

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

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

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

Plotly goes beyond bar plots; you can make scatter plotsbox plots, pie charts, histograms, heatmaps, and many other kinds of plots with it, which makes it a powerful tool for diverse data visualization tasks. Whether you want to forecast stock market trends, analyze stock market patterns with dynamic visualizations, or map geospatial information, Plotly provides the tools you need to bring your data to life across different domains.

Conclusion

Plotly Graph Objects provides a powerful and flexible way to create interactive and customizable bar plots in Python. With Plotly, we can easily visualize categorical data, compare values across different categories, and customize our plots to meet specific requirements. The library offers an extensive range of parameters and features, allowing users to fine-tune the appearance and behavior of their bar plots. Additionally, Plotly’s interactive capabilities enable data exploration through tooltips, legends, and zooming, making it a valuable tool for both data analysis and data communication. Whether we’re creating simple bar charts or more complex visualizations, Plotly Graph Objects empowers us to present our data effectively and engage our audience with interactive and informative bar plots.

Become a data analyst with our comprehensive learning path!

Ready to kickstart your career as a Data Analyst? Our "Become a Data Analyst" path is designed to take you from your first line of code to landing your first job.

Whether you’re a beginner or looking to transition into a data-driven career, this step-by-step journey will equip you with the skills to turn raw data into actionable insights. Develop expertise in data cleaning, analysis, and storytelling to make informed decisions and drive business success. With our AI mentor by your side, you’ll tackle challenges with personalized guidance. Start your data analytics career today and make your mark in the world of data!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What types of bar charts are available when using Plotly?

The common types of bar charts in Plotly include vertical bars, horizontal bars, stacked bars, and grouped bars.


What is the go.Bar function?

The go.Bar() function in Plotly Graph Objects is used to create a bar plot, where each bar represents data from a category.


How to customize a bar plot in Python

You can customize a bar plot in Python by changing colors, labels, text, and layout using parameters like marker, text, and layout in Plotly.


What is the difference between Plotly Go and Express?

Plotly Graph Objects go gives more control for customizing charts, while Plotly Express is simpler and faster for making basic plots with fewer settings.


Free Resources

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