Pie Charts in Python

How to make Pie Charts.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Try Plotly Studio now.

A pie chart is a circular statistical chart, which is divided into sectors to illustrate numerical proportion.

If you're looking instead for a multilevel hierarchical pie-like chart, go to the Sunburst tutorial.

Pie chart with plotly express

Plotly Express is the easy-to-use, high-level interface to Plotly, which operates on a variety of types of data and produces easy-to-style figures.

In px.pie, data visualized by the sectors of the pie is set in values. The sector labels are set in names.

In [1]:
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Europe'")
df.loc[df['pop'] < 2.e6, 'country'] = 'Other countries' # Represent only large countries
fig = px.pie(df, values='pop', names='country', title='Population of European continent')
fig.show()

Pie chart with repeated labels

Lines of the dataframe with the same value for names are grouped together in the same sector.

In [2]:
import plotly.express as px
# This dataframe has 244 lines, but 4 distinct values for `day`
df = px.data.tips()
fig = px.pie(df, values='tip', names='day')
fig.show()

Pie chart in Dash

Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash, click "Download" to get the code and run python app.py.

Get started with the official Dash docs and learn how to effortlessly style & publish apps like this with Dash Enterprise or Plotly Cloud.

Out[3]:

Sign up for Dash Club → Free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture. Join now.

Setting the color of pie sectors with px.pie

In [4]:
import plotly.express as px
df = px.data.tips()
fig = px.pie(df, values='tip', names='day', color_discrete_sequence=px.colors.sequential.RdBu)
fig.show()

Using an explicit mapping for discrete colors

For more information about discrete colors, see the dedicated page.

In [5]:
import plotly.express as px
df = px.data.tips()
fig = px.pie(df, values='tip', names='day', color='day',
             color_discrete_map={'Thur':'lightcyan',
                                 'Fri':'cyan',
                                 'Sat':'royalblue',
                                 'Sun':'darkblue'})
fig.show()

Customizing a pie chart created with px.pie

In the example below, we first create a pie chart with px,pie, using some of its options such as hover_data (which columns should appear in the hover) or labels (renaming column names). For further tuning, we call fig.update_traces to set other parameters of the chart (you can also use fig.update_layout for changing the layout).

In [6]:
import