Creating Pie Charts with Python’s Matplotlib
Pie charts are a circular statistical graphic that uses slices to illustrate numerical proportions. This type of chart is commonly used to present data and insights from opinion polls, market research, and surveys.
In this article, we will learn how to create a basic pie chart using Python’s Matplotlib library.
Creating Sample Data
To get started with creating a pie chart, we first need to create some sample data. In this case, let’s create a sample dataset of sport preferences of a small group of people. The data could look like this:
- Football: 35%
- Basketball: 25%
- Baseball: 20%
- Soccer: 15%
- Hockey: 5%
Plotting the Pie Chart
Now that we have sample data, we can start plotting the pie chart. But before we do that, we need to make sure that we import the Matplotlib library into our Python environment by typing “import matplotlib.pyplot as plt” at the beginning of our script.
Once we have imported the library, we can now use the “pie” function to plot our chart. To plot our chart, we need to specify the values we want to plot and the labels we want to use. In this case, the values refer to the numerical proportions for each sport, and the labels refer to the sport name.
Here is the code to plot our basic pie chart:
import matplotlib.pyplot as plt
values = [35, 25, 20, 15, 5]
labels = ['Football', 'Basketball', 'Baseball', 'Soccer', 'Hockey']
plt.pie(values, labels=labels)
plt.show()
In this code, we first define the values and labels that we want to plot. We then use the “pie” function to create the chart using the values and labels we defined. Finally, we use the “show” function to display the chart.
When we run this code, we should get a basic pie chart that shows the numerical proportions for each sport. As we can see from the chart, Football is the most preferred sport, with 35% of the respondents selecting it. Basketball is the second-most preferred sport, with 25% of the respondents selecting it. The other sports are less preferred, with Hockey being the least preferred sport, with only 5% of the respondents selecting it.
In conclusion, pie charts are a useful tool for presenting numerical proportions. They are commonly used in polls and surveys as an easy way to see how people responded to a question. In this article, we learned how to create a basic pie chart using Python’s Matplotlib library. By using labels and values, we were able to create a customized chart that accurately represents our sample data.
Customizing Pie Charts
Remember that in Matplotlib, there are many options for customizing pie charts, such as adding colors, exploding slices, and adding legends. With practice, you can create professional-looking charts that effectively communicate your insights and data.
Making a Slice Pop-out
One way to make certain slices stand out is to use the “explode” parameter. This parameter allows us to “explode” or pop-out one or more slices from the pie chart. To use this parameter, we first need to define a radius for each slice we want to “explode”. The radius is defined as a fraction of the pie’s radius. For instance, if we want to “explode” the first slice by 0.1, we would define a radius of 0.1 for that slice.
Here’s the code to add an explosion to the Football slice:
import matplotlib.pyplot as plt
values = [35, 25, 20, 15, 5]
labels = ['Football', 'Basketball', 'Baseball', 'Soccer', 'Hockey']
explode = (0.1, 0, 0, 0, 0)
plt.pie(values, labels=labels, explode=explode)
plt.show()
When we run this code, we should get a pie chart where the Football slice is slightly popped-out. Notice that we passed the “explode” parameter as a tuple with five values. The first value is 0.1, which is the radius we defined for the Football slice. By default, the “explode” parameter is set to None, which means that all slices have the same radius.
Rotating the Pie Chart
Another way to customize pie charts is to rotate them. By default, the first slice is positioned at the 3 o’clock position, which means that slices are positioned counterclockwise. We can change this position by using the “startangle” parameter. The “startangle” parameter sets the angle from which the first slice starts. A value of 0 means that the first slice starts at 3 o’clock, a value of 90 means that the first slice starts at 12 o’clock, and so on.
Here’s the code to rotate the pie chart 90 degrees:
import matplotlib.pyplot as plt
values = [35, 25, 20, 15, 5]
labels = ['Football', 'Basketball', 'Baseball', 'Soccer', 'Hockey']
plt.pie(values, labels=labels, startangle=90)
plt.show()
When we run this code, we should get a pie chart where the Football slice starts at 12 o’clock position. Notice that we passed the “startangle” parameter with a value of 90. This has rotated the pie chart by 90 degrees counterclockwise.
Displaying Percentages
It’s often useful to display percentages next to each slice to give the reader a better sense of the relative sizes of each slice. We can do this by using the “autopct” parameter. This parameter is used to format and display each slice’s percentage.
By default, the percentage is displayed with one decimal place. Here’s the code to display percentages with a precision of two decimal places:
import matplotlib.pyplot as plt
values = [35, 25, 20, 15, 5]
labels = ['Football', 'Basketball', 'Baseball', 'Soccer', 'Hockey']
plt.pie(values, labels=labels, autopct='%.2f%%')
plt.show()
When we run this code, we should get a pie chart where each slice’s percentage is displayed with a precision of two decimal places. Notice that we passed the “autopct” parameter with a string formatting expression that displays the percentage with two decimal places followed by the percentage sign (“%”).
Customizing Colors
Another way to customize pie charts is to select colors that convey the data’s message and match the context in which it’s presented. Matplotlib provides a colorful palette that we can use to customize our chart’s colors easily. For instance, we can use the “tab20” palette to create a chart with distinct and vibrant colors.
Here’s the code to customize our chart’s colors:
import matplotlib.pyplot as plt
values = [35, 25, 20, 15, 5]
labels = ['Football', 'Basketball', 'Baseball', 'Soccer', 'Hockey']
colors = plt.get_cmap('tab20').colors
plt.pie(values, labels=labels, colors=colors)
plt.show()
When we run this code, we should get a pie chart with vibrant colors for each slice. Notice that we used the “get_cmap” function to return a palette with 20 distinct colors, and we passed the “colors” parameter with the returned colors.
Displaying Color Codes
Finally, it’s often useful to display color codes next to each slice to allow readers to match colors to data. We can do this by using the “patches” and “legend” functions. The “patches” function returns a list of “Patch” objects, which are used to draw each slice. We can use the “legend” function to display these objects and their associated labels.
Here’s the code to display color codes:
import matplotlib.pyplot as plt
values = [35, 25, 20, 15, 5]
labels = ['Football', 'Basketball', 'Baseball', 'Soccer', 'Hockey']
colors = plt.get_cmap('tab20').colors
patches, texts = plt.pie(values, labels=labels, colors=colors)
plt.legend(patches, labels, loc="best")
plt.show()
When we run this code, we should get a pie chart with color codes displayed next to each slice. Notice that we passed the “patches” and “labels” variables to the “legend” function as arguments. The “loc” parameter sets the position of the legend.
Summary
In this section, we learned how to customize pie charts using Matplotlib. We learned how to make a slice pop-out, rotate the pie chart, display percentages, customize colors, and display color codes. Pie charts are an effective way to convey data and insights, and customizing them can help increase their impact and readability.
Conclusion
Pie charts are an essential tool for visually presenting numerical proportions, whether in surveys, opinion polls, or market research. In this article, we learned how to create a basic pie chart using Python’s Matplotlib library and how to customize it to make it more visually appealing and informative. We explored various customization techniques, such as making slices pop-out, rotating the chart, displaying percentages, using custom colors, and displaying color codes. By using these techniques, we can create clear and accessible pie charts that best represent our data.
Remember that designing a pie chart is not just about displaying data; it’s about presenting data in a way that is easy to digest and understand. And with these techniques, you can design compelling pie charts that are both informative and visually attractive.