Skip to content

Commit ac4cca2

Browse files
committed
Added Content: Pie Charts in Matplotlib
1 parent c9860ed commit ac4cca2

11 files changed

+234
-0
lines changed
Loading
Loading
Loading
Loading
Loading
Loading
16.6 KB
Loading
Loading
27.4 KB
Loading
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
# List of sections
22

33
- [Installing Matplotlib](matplotlib_installation.md)
4+
- [Pie Charts in Matplotlib](matplotlib_pie_charts.md)
Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
# Pie Charts in Matplotlib
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+
## Prerequisites
8+
9+
Before creating pie charts in matplotlib you must ensure that you have Python as well as Matplotlib installed on your system.
10+
11+
## Creating a simple pie chart with `pie()` method
12+
13+
A basic pie chart can be created with `pie()` method in `matplotlib.pyplot`.
14+
15+
```Python
16+
import matplotlib.pyplot as plt
17+
18+
# Creating dataset
19+
labels = ['A','B','C','D','E']
20+
data = [10,20,30,40,50]
21+
22+
# Creating Plot
23+
plt.pie(data, labels=labels)
24+
25+
# Show plot
26+
plt.show()
27+
```
28+
29+
When executed, this would show the following pie chart:
30+
31+
![Basic Pie Chart](images/basic_pie_chart.png)
32+
33+
Note that the slices of the pie are labelled according to their corresponding proportion in the `data` as a whole.
34+
35+
The `pie()` function takes arguments that describes the layout of the pie chart.
36+
37+
Here, `plt.pie(data, labels=labels)` is used to specify that the pie chart is to be plotted by taking the values from array `data` and the fractional area of each slice is represented by **data/sum(data)**. The array `labels` represents the labels of slices corresponding to each value in `data`.
38+
39+
You can customize the graph further like specifying custom colors for slices, exploding slices, labeling wedges (slices), etc. These will be explored in the upcoming sections.
40+
41+
## Customizing Pie Chart in Matplotlib
42+
43+
For creating customized plots, it is highly recommended to create the plots using `matplotlib.pyplot.subplots()`, otherwise it is difficult to apply the customizations in the newer versions of Matplotlib.
44+
45+
### Coloring Slices
46+
47+
You can add custom set of colors to the slices by passing an array of colors to `colors` parameter in `pie()` method.
48+
49+
```Python
50+
import matplotlib.pyplot as plt
51+
52+
# Creating dataset
53+
labels = ['A','B','C','D','E']
54+
data = [10,20,30,40,50]
55+
colors = ['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:pink']
56+
57+
# Creating plot using matplotlib.pyplot.subplots()
58+
fig, ax = plt.subplots()
59+
ax.pie(data, labels=labels, colors=colors)
60+
61+
# Show plot
62+
plt.show()
63+
```
64+
![Coloring Slices](images/coloring_slices.png)
65+
66+
Here, we have created a `matplotlib.pyplot.subplots()` object which returns a `Figure` object `fig` as well as an `Axes` object `ax` both of which are used for customizing the pie chart.
67+
68+
**Note:** Each slice of the pie chart is a `patches.Wedge` object; therefore in addition to the customizations shown here, each wedge can be customized using the `wedgeprops` argument which takes Python dictionary as parameter with name values pairs denoting the wedge properties like linewidth, edgecolor, etc.
69+
70+
### Hatching Slices
71+
72+
To make the pie chart more pleasing, you can pass a list of hatch patters to `hatch` parameter to set the pattern of each slice.
73+
74+
```Python
75+
import matplotlib.pyplot as plt
76+
77+
# Creating dataset
78+
labels = ['A','B','C','D','E']
79+
data = [10,20,30,40,50]
80+
colors = ['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:pink']
81+
hatch = ['*O', 'oO', 'OO', '.||.', '|*|'] # Hatch patterns
82+
83+
# Creating plot
84+
fig, ax = plt.subplots()
85+
ax.pie(data, labels=labels, colors=colors, hatch=hatch)
86+
87+
# Show plot
88+
plt.show()
89+
```
90+
![Hatch Patterns](images/hatch_patterns.png)
91+
92+
You can try and test your own beautiful hatch patters!
93+
94+
### Labeling Slices
95+
96+
You can pass a function or format string to `autopct` parameter to label slices.
97+
98+
An example in shown here:
99+
100+
```Python
101+
import matplotlib.pyplot as plt
102+
103+
# Creating dataset
104+
labels = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
105+
data = [11,9,17,4,7]
106+
colors=['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:pink']
107+
108+
# Creating plot
109+
fig, ax = plt.subplots()
110+
ax.pie(data, labels=labels, colors=colors, autopct='%1.1f%%')
111+
112+
# Show plot
113+
plt.show()
114+
```
115+
![Autopct Example](images/autopct.png)
116+
117+
Here, `autopct='%1.1f%%'` specifies that the wedges (slices) have to be labelled corresponding to the percentage proportion which they occupy out of 100% with precision upto 1 decimal places.
118+
119+
### Exploding Slices
120+
121+
The explode parameter separates a portion of the chart. You can explode slices by passing an array of numbers to `explode` parameter.
122+
123+
```Python
124+
import matplotlib.pyplot as plt
125+
126+
# Creating dataset
127+
labels = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
128+
data = [11,9,17,4,7]
129+
colors=['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:pink']
130+
131+
# Explode only the first slice, i.e 'Rose'
132+
explode = [0.1, 0, 0, 0, 0]
133+
134+
# Creating plot
135+
fig, ax = plt.subplots()
136+
ax.pie(data, labels=labels, colors=colors, explode=explode, autopct='%1.1f%%')
137+
138+
# Show plot
139+
plt.show()
140+
```
141+
![Explode Slice](images/explode_slice.png)
142+
143+
### Shading Slices
144+
145+
You can add shadow to slices by passing `shadow=True` in `pie()` method.
146+
147+
```Python
148+
import matplotlib.pyplot as plt
149+
150+
# Creating dataset
151+
labels = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
152+
data = [11,9,17,4,7]
153+
colors=['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:pink']
154+
155+
# Explode only the first slice, i.e 'Rose'
156+
explode = [0.1, 0, 0, 0, 0]
157+
158+
# Creating plot
159+
fig, ax = plt.subplots()
160+
ax.pie(data, labels=labels, colors=colors, explode=explode, shadow=True, autopct='%1.1f%%')
161+
162+
# Show plot
163+
plt.show()
164+
```
165+
![Shadow](images/shadow.png)
166+
167+
### Rotating Slices
168+
169+
You can rotate slices by passing a custom start angle value to the `startangle` parameter.
170+
171+
```Python
172+
import matplotlib.pyplot as plt
173+
174+
# Creating dataset
175+
labels = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
176+
data = [11,9,17,4,7]
177+
colors=['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:pink']
178+
179+
# Creating plot
180+
fig, ax = plt.subplots()
181+
ax.pie(data, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%')
182+
183+
# Show plot
184+
plt.show()
185+
```
186+
![Rotating Slices](images/rotating_slices.png)
187+
188+
The default `startangle` is 0, which would start the first slice ('Rose') on the positive x-axis. This example sets `startangle=90` such that all the slices are rotated counter-clockwise by 90 degrees, and the `'Rose'` slice starts on the positive y-axis.
189+
190+
### Controlling Size of Pie Chart
191+
192+
In addition to the size of figure, you can also control the size of pie chart using the `radius` parameter.
193+
194+
```Python
195+
import matplotlib.pyplot as plt
196+
197+
# Creating dataset
198+
labels = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
199+
data = [11,9,17,4,7]
200+
colors=['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:pink']
201+
202+
# Creating plot
203+
fig, ax = plt.subplots()
204+
ax.pie(data, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%', textprops={'size': 'smaller'}, radius=0.7)
205+
206+
# Show plot
207+
plt.show()
208+
```
209+
![Controlling Size](images/radius.png)
210+
211+
Note that `textprops` is an additional argument which can be used for controlling the propoerties of any text in the pie chart. In this case, we have specified that the size of text should be smaller. There are many more such properties available in `textprops`.
212+
213+
### Adding Legends
214+
215+
You can also use legends to act like a label to slices, like this:
216+
217+
```Python
218+
import matplotlib.pyplot as plt
219+
220+
# Creating dataset
221+
labels = ['Rose','Tulip','Marigold','Sunflower','Daffodil']
222+
data = [11,9,17,4,7]
223+
colors=['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:pink']
224+
225+
# Creating plot
226+
fig, ax = plt.subplots(figsize=(7,7))
227+
ax.pie(data, colors=colors, startangle=90, autopct='%1.1f%%', radius=0.7)
228+
plt.legend(labels, title="Flowers")
229+
230+
# Show plot
231+
plt.show()
232+
```
233+
![Legends](images/legends.png)

0 commit comments

Comments
 (0)