Plotly Graph Objects is a Python library that provides a flexible and powerful way to create interactive data visualizations. It’s 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.
A pie plot in Plotly Graph Objects is a type of chart that represents data in a circular statistical graphic. It’s often used to show the proportion of each category relative to the whole. In a pie plot, the entire pie represents 100%, and each wedge or slice corresponds to a specific category, with the size of each slice proportional to the percentage it represents.
The following are some key features of pie plots using Plotly Graph Objects:
Data Input: We can create pie plots by providing a list of values representing the sizes of the pie slices. These values are often numeric, and Plotly will automatically calculate the percentage of the whole for each slice.
Labels: We can add labels to each pie slice to provide additional information. Labels can be positioned inside or outside the slices, and we can customize their appearance, such as font size and color.
Hover information: When we hover over a pie slice, we can display additional information using tooltips. This is useful for showing details about each slice when the user interacts with the plot.
Colors: We can specify custom colors for each pie slice to make our plot more visually appealing or to highlight specific slices. Plotly provides a range of color scales to choose from.
Exploded slices: We can explode or separate one or more slices from the center of the pie chart to emphasize them. This can be done by specifying an offset for the exploded slices.
Title and legend: We can add a title to the pie chart and include a legend to provide context for the data. Legends can be positioned in different locations, such as the top, bottom, left, or right.
Customize text: We have control over the text displayed in labels, tooltips, and legends. This allows us to format and style text as needed.
Responsive design: Plotly charts are responsive by default, which means they automatically adjust to the size of the container in which they are displayed.
Interactive features: Pie plots created with Plotly are highly interactive. Users can click the slices to explode them, toggle legend items to hide/show slices, and more.
Customization: Plotly provides extensive customization options for fine-tuning the appearance of our pie chart, including fonts, colors, borders, and more.
The pie plot syntax typically follows this structure:
import plotly.graph_objects as gopie_plot = go.Figure(go.Pie(labels=labels, # Labels for the pie slicesvalues=values, # Values for the pie slicesname='Pie Chart', # Name for the trace (used in legends)pull=[0, 0.2, 0], # Specify how much each slice should be pulled from the center (optional)textinfo='percent+label', # Information to display on the pie sliceshoverinfo='label+percent',# Information to display on hovermarker=dict(colors=['blue', 'green', 'red'], line=dict(color='white', width=2)) # Customize colors and borders))
The following are the key parameters for creating a pie plot using Plotly Graph Objects:
labels
(list): These are the labels for the pie slices.
values
(list or array): These are the values or sizes of the pie slices.
name
(str): This is the name for the trace, which is used in legends.
pull
(list of floats, optional): This determines how much each slice is pulled from the center of the pie chart. Each value in the list corresponds to a slice, and higher values pull the slice farther from the center.
textinfo
(str, optional): This specifies what information to display on or next to the pie slices. Options include 'label'
, 'value'
, 'percent'
, 'percent+label'
, 'percent+value'
, and more.
hoverinfo
(str, optional): This specifies what information to display when hovering over the pie slices. Options include 'label'
, 'value'
, 'percent'
, 'text'
, 'name'
, and combinations of these (e.g., 'label+percent'
).
hole
(float, optional): This creates a hole in the center of the pie chart, turning it into a donut chart. The value represents the size of the hole as a fraction of the radius.
domain
(dict, optional): Allows you to specify the position and size of the pie chart within the plotting area using the 'x'
and 'y'
keys.
marker
(dict, optional): Customization options for the appearance of the pie slices, including colors, line properties, and more.
When we create a visualization like a pie plot using the go.Pie
trace and the go.Figure
constructor in Plotly Graph Objects, we’re essentially creating a figure object that represents our pie chart. The figure object contains all the necessary information about our pie chart, including the data, trace, layout, and any additional settings or customizations we’ve applied to create an interactive and informative pie chart.
In the following playground, we create a pie plot using a sample dataset called gapminder provided by Plotly Express. Attributes of the gapminder
dataset (country
, continent
, year
, lifeExp
, pop
, gdpPercap
and species
) defined as follows:
country
: The name of the country for the data point
continent
: The continent to which the country belongs
year
: The year in which the data was recorded
lifeExp
: The life expectancy of the population in years
pop
: The population of the country
gdpPercap
: The gross domestic product (GDP) per capita, which is the economic output per person in USD
iso_alpha
: The ISO alpha-3 code representing the country
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 gapminder
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 13: We group the DataFrame df
by the 'continent'
column and calculate the sum of the 'pop'
column within each continent. The result is stored in the continent_population
DataFrame, which contains two columns: 'continent'
and the total population ('pop'
) for each continent.
Lines 16–22: Create the pie chart using Plotly Graph Objects. It uses the go.Pie
trace within a go.Figure
object (fig
).
labels
are set to the continent
values from the continent_population
DataFrame.
values
are set to the corresponding population values.
textinfo
is configured to display both the percentage and the label on each pie slice.
hole
specifies that a 30% hole should be created in the center of the pie chart, making it a donut chart.
marker
is used to specify the colors for the pie slices based on Plotly's color palette.
Line 15–28: Customize the layout of the pie chart by updating the fig
object.
title
sets the title of the chart to World Population by Continent
.
showlegend
is set to True
to display the legend on the chart, showing the labels for each continent.
Line 31: Display the finalized pie plot figure using the show()
method.
Creating pie plots using Plotly Graph Objects provides a powerful and flexible way to visualize data distributions, particularly when dealing with categorical data. With the ability to customize label colors and even transform your pie chart into a donut chart, Plotly Graph Objects offers a range of options for creating informative and visually appealing representations of data. Whether you’re exploring proportions, percentages, or comparing categories, pie plots in Plotly Graph Objects can effectively convey insights, making them a valuable tool in data analysis and visualization workflows.
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