How to create a pie 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’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.

Features of the pie plot in Plotly Graph Objects

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.

Syntax

The pie plot syntax typically follows this structure:

import plotly.graph_objects as go
pie_plot = go.Figure(go.Pie(
labels=labels, # Labels for the pie slices
values=values, # Values for the pie slices
name='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 slices
hoverinfo='label+percent',# Information to display on hover
marker=dict(colors=['blue', 'green', 'red'], line=dict(color='white', width=2)) # Customize colors and borders
))
Syntax of the pie plot

Parameters

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.

Return type

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.

Implementation

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 &
Visualizing world population by continent with a donut chart using Plotly Graph Objects

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 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.

Conclusion

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.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved