×

Pie Chart with Plotly

pie chart (or a circle chart) is a circular statistical graphic, which is divided into slices to illustrate numerical proportion. In a pie chart, the arc length of each slice and consequently its central angle and area is proportional to the quantity it represents.

Pie charts are very widely used in the business world and the mass media.

Pie Chart Wiki

Submodules in Plotly to create Plots

Plotly supports two submodules for creating various plots such as line plot, bar plot, etc., that are following:

  • Plotly Express
import plotly.express as px
  • Plotly Graph objects
import plotly.graph_objects as go

We can choose to use any of the modules but plotly.express is widely used, because plotly.express needs less number of lines of code in order to create any plot.

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.

  • Import the plotly express module.
import plotly.express as px
  • Get the data frame to use it in the plot.
data_frame = px.data.gapminder().query("year == 2007").query("country == 'Canada')
  • With px.pie, each row of the DataFrame can be represented in a pie chart. Create the pie chart and store its object.
fig = px.pie(df, values='pop', names='country')
  • Show the plot via show() – method, using object of the plot created.
fig.show()
Complete Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007").query("continent == 'Europe'")
fig = px.pie(df, values='pop', names='country')
fig.show()
Output
Pie Chart Plotly Express

Pie chart with repeated labels

Lines of the dataframe with the same value for names are grouped together in the same sector. For example, consider tips data frame from plotly express.

df = px.data.tips()
print(px.data.tips().head())

head() – method allows to get insight of any data frame.

   | total_bill|  tip |   sex  | smoker | day |  time  | size
 ---|-----------|------|--------|--------|-----|--------|--
 0  |   16.99   | 1.01 | Female |   No   | Sun | Dinner | 2
 1  |   10.34   | 1.66 |  Male  |   No   | Sun | Dinner | 3
 2  |   21.01   | 3.50 |  Male  |   No   | Sun | Dinner | 3
 3  |   23.68   | 3.31 |  Male  |   No   | Sun | Dinner | 2
 4  |   24.59   | 3.61 | Female |   No   | Sun | Dinner | 4

Let’s group data in day column:

import plotly.express as px

df = px.data.tips()
print(px.data.tips().head())
fig = px.pie(df, values='tip', names='day') #name attribute
fig.show()

Output

Group Repeated Label Pie Chart Plotly

Setting the color of sectors in Pie Chart

The color of the sectors in the pie chart can also be customized – using color sequences. Different colors help to distinguish the data from each other, which helps to understand the data more efficiently.

Color sequences are lists of colors to be mapped onto discrete data values. Most Plotly Express functions (i.e px.bar(), px.pie() etc..) accept a color argument which automatically assigns data values to discrete colors if the data is non-numeric.

By default, Plotly Express will use the color sequence from the active template’s layout.colorway attribute, and the default active template is plotly which uses the plotly color sequence.

You can choose any of the following built-in sequential color sequences from the px.colors.sequential module.

import plotly.express as px
fig = px.colors.sequential.swatches()
fig.show()
Output
Sequential Swatches

Color Discrete Sequence

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()
Output
Sector Colors

Explicit mapping for discrete colors

You can directly map colors to different data values in the plot with color_discrete_map.

Title attribute can be used to set the title to the plot.

import plotly.express as px
df = px.data.tips()

fig = px.pie(df,
    values='tip', 
    names='day', 
    color='day',
    color_discrete_map={'Thur':'red',
                        'Fri':'cyan',
                        'Sat':'blue',
                        'Sun':'pink'},
    title = "Explicit Colour Mapping")
fig.show()
Output
Explicit Color Mapping Plotly Express

Customize Text inside the Sectors

We can also choose to customize what information to display in the pie chart as well as we can set the position of the text. We call fig.update_traces to set our parameters of the chart – textposition, textinfo.

import plotly.express as px
df = px.data.tips()

fig = px.pie(df, 
    values='tip', 
    names='day',
    title="Pie Chart with Custom Text info",)

fig.update_traces(textposition = 'outside' , textinfo = 'percent+label')
fig.show()
Output
Textinfo Pie Chart Plotly

Pie Chart with Plotly Graph Objects

  • Import the plotly graph objects.

plotly graph_objects module is typically imported as go

import plotly.graph_objects as go
  • Get the data frame to use it in the plot.
countries=['India', 'Australia',
           'Japan', 'America',
           'Russia']
 
values = [4500, 2500, 1053, 500,
          3200]

When using Plotly graph objects first we have to create a figure(i.e a canvas) in which we actually add the plot. For creating a figure we have to just call the Figure() – method of the graph_objects – submodule.

go_fig = go.Figure()
  • Create the plot – Plotly graph objects has Bar() – method for the Bar graph.
obj = go.Pie(x = countries, y = values)

Add the plot object to the Figure(or Canvas), for adding the plot into the figure(or canvas) created, we have to use add_trace() – method.

go_fig.add_trace(obj)
  • Show the plot via show() – method, using object of the figure created.
go_fig.show()
Complete Code
import plotly.graph_objects as go

countries=['India', 'Australia', 'Japan', 'America', 'Russia']
values = [4500, 2500, 1053, 500, 3200]

go_fig = go.Figure()

obj = go.Pie(labels = countries, values = values)
go_fig.add_trace(obj)
go_fig.show()
Output
Pie Chart Plotly Graph Objects

Styled Pie Chart

Set Colour of the Sectors

Colors can be given as RGB triplets or hexadecimal strings, or with CSS color names as below.

  • Create a custom colours list.
colors = ['gold', 'mediumturquoise', 'darkorange', 'lightgreen']
  • Create the figure and the plot add the plot to the figure.
col_obj = go.Pie(labels = countries, values = values)
go_fig.add_trace(obj)
  • Now with the update_traces() – method add the customization to the plot in the figure.
go_fig.update_traces(marker = dict(colors = colors, 
                     line=dict(color='#000000', width=2)))
Complete Code
import plotly.graph_objects as go

countries=['India', 'Australia', 'Japan', 'America', 'Russia']
values = [4500, 2500, 1053, 500, 3200]

go_fig = go.Figure()
colors = ['gold', 'mediumturquoise', 'darkorange', 'lightgreen']
col_obj = go.Pie(labels = countries, values = values)
go_fig.add_trace(obj)
go_fig.update_traces(marker = dict(colors = colors, line=dict(color='#000000', width=2)))
go_fig.show()
Output
Styled Graph Plotly Graph Objects

Set the Fontsize of the Labels

If you want all the text labels to have the same size, you can use the uniformtext layout parameter. The minsize attribute sets the font size and the mode attribute sets what happens for labels that cannot fit with the desired font size: either hide them or show them with overflow.

go_fig.update_layout(uniformtext_minsize=35, uniformtext_mode='hide')
import plotly.graph_objects as go

countries=['India', 'Australia', 'Japan', 'America', 'Russia']
values = [4500, 2500, 1053, 500, 3200]

go_fig = go.Figure()
colors = ['gold', 'mediumturquoise', 'darkorange', 'lightgreen']
col_obj = go.Pie(labels = countries, values = values)
go_fig.add_trace(obj)
go_fig.update_traces(marker = dict(colors = colors, line=dict(color='#000000', width=2)))
go_fig.update_layout(uniformtext_minsize=35, uniformtext_mode='hide')#Update layout
go_fig.show()
Output
Custom Font Size Plotly

Set the Orientation Of the Labels

The insidetextorientation – attribute controls the orientation of text inside sectors. Using “horizontal”, “radial”, “tangential” forces text to be horizontal, radial or tangential.

Default orientation is “auto”

  • With “auto” the texts may automatically be rotated to fit with the maximum size inside the slice.
or_obj = go.Pie(
    labels = countries, 
    values = values, 
    insidetextorientation = 'tangential')
go_fig.add_trace(or_obj)
go_fig.show()
Output
Orientation Text Plotly

Pulling sectors out from the center

For a “pulled-out” or “exploded” layout of the pie chart, use the pull argument. It can be a scalar for pulling all sectors or an array to pull only some of the sectors.

Pull as a Scalar Value

pull_obj = go.Pie(
    labels = countries, 
    values = values,
    pull = 0.1)
go_fig.add_trace(pull_obj)
go_fig.show()
Output
Pull Sectors From Center Plotly Abstract

Pull as an Array Value

import plotly.graph_objects as go

countries=['India', 'Australia', 'Japan', 'America', 'Russia']
values = [4500, 2500, 1053, 500, 3200]

go_fig = go.Figure()

pu_obj = go.Pie(
    labels = countries, 
    values = values,
    pull = [0, 0, 0, 0.2]) #Array passed

go_fig.add_trace(pu_obj)
go_fig.show()
Output
Pull Sector Out Of Center Plotly Array

Donut Charts

A Donut chart is a variant of the pie chart, with a blank center allowing for additional information about the data as a whole to be included.

We can create a Donut chart by just setting up the hole – attribute of the Pie() – method of Plotly Graph Objects.

hole=0.5 #Any float or integer value
import plotly.graph_objects as go

countries=['India', 'Australia', 'Japan', 'America', 'Russia']
values = [4500, 2500, 1053, 500, 3200]

go_fig = go.Figure()

do_fig = go.Pie(
    labels=countries, 
    values=values, 
    hole=0.5) #The hole attribute
go_fig.add_trace(do_fig)
go_fig.show()
Output
Donut Chart Plotly