Skip to content

Commit 2982d6d

Browse files
authored
Merge pull request animator#1279 from piyush-poddar/introduction-to-pie-charts-in-plotly
Introduction to Pie Charts in Plotly
2 parents 1d0af09 + 7e996f4 commit 2982d6d

File tree

9 files changed

+222
-0
lines changed

9 files changed

+222
-0
lines changed
Loading
Loading

contrib/plotting-visualization/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@
1010
- [Seaborn Plotting Functions](seaborn-plotting.md)
1111
- [Getting started with Seaborn](seaborn-basics.md)
1212
- [Bar Plots in Plotly](plotly-bar-plots.md)
13+
- [Pie Charts in Plotly](plotly-pie-charts.md)
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
# Pie Charts in Plotly
2+
3+
A pie chart is a type of graph that represents the data in the circular graph. The slices of pie show the relative size of the data, and it is a type of pictorial representation of data. A pie chart requires a list of categorical variables and numerical variables. Here, the term "pie" represents the whole, and the "slices" represent the parts of the whole.
4+
5+
Pie charts are commonly used in business presentations like sales, operations, survey results, resources, etc. as they are pleasing to the eye and provide a quick summary.
6+
7+
Plotly is a very powerful library for creating modern visualizations and it provides a very easy and intuitive method to create highly customized pie charts.
8+
9+
## Prerequisites
10+
11+
Before creating bar plots in Plotly you must ensure that you have Python, Plotly and Pandas installed on your system.
12+
13+
## Introduction
14+
15+
There are various ways to create pie charts in `plotly`. One of the prominent and easiest one is using `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. On the other hand you can also use `plotly.graph_objects` to create various plots.
16+
17+
Here, we'll be using `plotly.express` to create the pie charts. Also we'll be converting our datasets into pandas DataFrames which makes it extremely convenient and easy to create charts.
18+
19+
Also, note that when you execute the codes in a simple python file, the output plot will be shown in your **browser**, rather than a pop-up window like in matplotlib. If you do not want that, it is **recommended to create the plots in a notebook (like jupyter)**. For this, install an additional library `nbformat`. This way you can see the output on the notebook itself, and can also render its format to png, jpg, etc.
20+
21+
## Creating a simple pie chart using `plotly.express.pie`
22+
23+
In `plotly.express.pie`, data visualized by the sectors of the pie is set in values. The sector labels are set in names.
24+
25+
```Python
26+
import plotly.express as px
27+
import pandas as pd
28+
29+
# Creating dataset
30+
flowers = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
31+
petals = [11,9,17,4,7]
32+
33+
# Converting dataset to pandas DataFrame
34+
dataset = {'flowers':flowers, 'petals':petals}
35+
df = pd.DataFrame(dataset)
36+
37+
# Creating pie chart
38+
fig = px.pie(df, values='petals', names='flowers')
39+
40+
# Showing plot
41+
fig.show()
42+
```
43+
![Basic Pie Chart](images/plotly-basic-pie-chart.png)
44+
45+
Here, we are first creating the dataset and converting it into Pandas DataFrames using dictionaries, with its keys being DataFrame columns. Next, we are plotting the pie chart by using `px.pie`. In the `values` and `names` parameters, we have to specify a column name in the DataFrame.
46+
47+
`px.pie(df, values='Petals', names='Flowers')` is used to specify that the pie chart is to be plotted by taking the values from column `Petals` and the fractional area of each slice is represented by **petal/sum(petals)**. The column `flowers` represents the labels of slices corresponding to each value in `petals`.
48+
49+
**Note:** When you generate the image using above code, it will show you an **interactive plot**, if you want image, you can download it from their itself.
50+
51+
## Customizing Pie Charts
52+
53+
### Adding title to the chart
54+
55+
Simply pass the title of your chart as a parameter in `px.pie`.
56+
57+
```Python
58+
import plotly.express as px
59+
import pandas as pd
60+
61+
# Creating dataset
62+
flowers = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
63+
petals = [11,9,17,4,7]
64+
65+
# Converting dataset to pandas DataFrame
66+
dataset = {'flowers':flowers, 'petals':petals}
67+
df = pd.DataFrame(dataset)
68+
69+
# Creating pie chart
70+
fig = px.pie(df, values='petals', names='flowers',
71+
title='Number of Petals in Flowers')
72+
73+
# Showing plot
74+
fig.show()
75+
```
76+
![Title in Pie Chart](images/plotly-pie-title.png)
77+
78+
### Coloring Slices
79+
80+
There are a lot of beautiful color scales available in plotly and can be found here [plotly color scales](https://plotly.com/python/builtin-colorscales/). Choose your favourite colorscale apply it like this:
81+
82+
```Python
83+
import plotly.express as px
84+
import pandas as pd
85+
86+
# Creating dataset
87+
flowers = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
88+
petals = [11,9,17,4,7]
89+
90+
# Converting dataset to pandas DataFrame
91+
dataset = {'flowers':flowers, 'petals':petals}
92+
df = pd.DataFrame(dataset)
93+
94+
# Creating pie chart
95+
fig = px.pie(df, values='petals', names='flowers',
96+
title='Number of Petals in Flowers',
97+
color_discrete_sequence=px.colors.sequential.Agsunset)
98+
99+
# Showing plot
100+
fig.show()
101+
```
102+
![Pie Chart Colors-1](images/plotly-pie-color-1.png)
103+
104+
You can also set custom colors for each label by passing it as a dictionary(map) in `color_discrete_map`, like this:
105+
106+
```Python
107+
import plotly.express as px
108+
import pandas as pd
109+
110+
# Creating dataset
111+
flowers = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
112+
petals = [11,9,17,4,7]
113+
114+
# Converting dataset to pandas DataFrame
115+
dataset = {'flowers':flowers, 'petals':petals}
116+
df = pd.DataFrame(dataset)
117+
118+
# Creating pie chart
119+
fig = px.pie(df, values='petals', names='flowers',
120+
title='Number of Petals in Flowers',
121+
color='flowers',
122+
color_discrete_map={'Rose':'red',
123+
'Tulip':'magenta',
124+
'Marigold':'green',
125+
'Sunflower':'yellow',
126+
'Daffodil':'royalblue'})
127+
128+
# Showing plot
129+
fig.show()
130+
```
131+
![Pie Chart Colors-1](images/plotly-pie-color-2.png)
132+
133+
### Labeling Slices
134+
135+
You can use `fig.update_traces` to effectively control the properties of text being displayed on your figure, for example if we want both flower name , petal count and percentage in our slices, we can do it like this:
136+
137+
```Python
138+
import plotly.express as px
139+
import pandas as pd
140+
141+
# Creating dataset
142+
flowers = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
143+
petals = [11,9,17,4,7]
144+
145+
# Converting dataset to pandas DataFrame
146+
dataset = {'flowers':flowers, 'petals':petals}
147+
df = pd.DataFrame(dataset)
148+
149+
# Creating pie chart
150+
fig = px.pie(df, values='petals', names='flowers',
151+
title='Number of Petals in Flowers')
152+
153+
# Updating text properties
154+
fig.update_traces(textposition='inside', textinfo='label+value+percent')
155+
156+
# Showing plot
157+
fig.show()
158+
```
159+
![Pie Labels](images/plotly-pie-labels.png)
160+
161+
### Pulling out a slice
162+
163+
To pull out a slice pass an array to parameter `pull` in `fig.update_traces` corresponding to the slices and amount to be pulled.
164+
165+
```Python
166+
import plotly.express as px
167+
import pandas as pd
168+
169+
# Creating dataset
170+
flowers = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
171+
petals = [11,9,17,4,7]
172+
173+
# Converting dataset to pandas DataFrame
174+
dataset = {'flowers':flowers, 'petals':petals}
175+
df = pd.DataFrame(dataset)
176+
177+
# Creating pie chart
178+
fig = px.pie(df, values='petals', names='flowers',
179+
title='Number of Petals in Flowers')
180+
181+
# Updating text properties
182+
fig.update_traces(textposition='inside', textinfo='label+value')
183+
184+
# Pulling out slice
185+
fig.update_traces(pull=[0,0,0,0.2,0])
186+
187+
# Showing plot
188+
fig.show()
189+
```
190+
![Slice Pull](images/plotly-pie-pull.png)
191+
192+
### Pattern Fills
193+
194+
You can also add patterns (hatches), in addition to colors in pie charts.
195+
196+
```Python
197+
import plotly.express as px
198+
import pandas as pd
199+
200+
# Creating dataset
201+
flowers = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
202+
petals = [11,9,17,4,7]
203+
204+
# Converting dataset to pandas DataFrame
205+
dataset = {'flowers':flowers, 'petals':petals}
206+
df = pd.DataFrame(dataset)
207+
208+
# Creating pie chart
209+
fig = px.pie(df, values='petals', names='flowers',
210+
title='Number of Petals in Flowers')
211+
212+
# Updating text properties
213+
fig.update_traces(textposition='outside', textinfo='label+value')
214+
215+
# Adding pattern fills
216+
fig.update_traces(marker=dict(pattern=dict(shape=[".", "/", "+", "-","+"])))
217+
218+
# Showing plot
219+
fig.show()
220+
```
221+
![Pattern Fills Pie Chart](images/plotly-pie-patterns.png)

0 commit comments

Comments
 (0)