Pie charts

Let's take a look at the fractions of gases that exist in our atmosphere. The following content shows the code and output for Nitrogen, which is 78 percent of our atmosphere, Oxygen, which is 21 percent, and Argon, which is 1 percent. Now, naturally, Nitrogen, Oxygen, and Argon are not exactly numerical values. Hence, we cannot really plot these things against each other in the standard way. This is where we can use a pie chart as a best practice to display these differences:

  1. First, we must set the aspect ratio to equal here. This gives a standard pie chart, as follows:
# Basic Pie Chart
fracs = (78, 21, 1)
labels = ('Nitrogen', 'Oxygen', 'Argon')
plt.pie(fracs, labels=labels);
plt.gca().set_aspect('equal')

We will get the following output:

  1. To customize the preceding pie chart, we can highlight the Oxygen part. We will add another tuple and call it explode argument. These tuple values can be used to pull slices out. Here, we can see that Oxygen was sliced out by 20 percent:

  1. The colors can also be changed in the same way by passing a tuple with the same length as the number of slices, as shown in the following code:
# colors
fracs = (78, 21, 1)
labels = ('Nitrogen', 'Oxygen', 'Argon')
plt.pie(fracs, colors=('k', 'c', 'g'), labels=labels);
plt.gca().set_aspect('equal')

We will get the following output:

  1. We can also add a shadow by setting the shadow keyword argument to True. By doing this, you get a nice little shadow:

  1. To change the radius of the pie chart so that it's 50 percent smaller, that is radius=0.5, we can use the following code:

  1. To show the percentages of the chart, we can insert autopct= "%2.0f %%". This will display the percentage values as well. This can either be a format string or a function that returns a string:

  1. We can also set pctdistance with what fraction or radius of the pie chart these labels get applied at. To have them near the edge, we can set this to 90 percent; that is 0.9:

  1. To have the labels near the radius, set it to 50 percent; that is 0.5:

By setting the pctdistance to 0.1, we get the labels 78 percent, 21 percent, and 1 percent much closer to the radius.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset