A pie chart is a circular statistical graphic, that is divided into several slices. And each slice represents a numerical proportion or a percentage. For example, let’s look into the titanic dataset. The dataset contains information about the embark town of each passenger. Let’s say we want to know what percentage of passengers embarked from each embark town. We can create a pie chart and see the numerical proportion of embark towns of passengers.
We can use the following Python code to plot the pie chart using the matplotlib Python library:
import pandas
from matplotlib import pyplot
df = pandas.read_csv("titanic.csv")
print(df.info())
series1 = df.embark_town.value_counts()
print(series1.index)
print(series1.values)
pyplot.pie(x=series1.values, labels=series1.index, autopct="%1.2f%%", explode=[0.05, 0.05, 0.05])
pyplot.savefig("matplotlib-pie-chart.png")
pyplot.close()
Here, df.embark_town.value_counts() creates a pandas Series that contain information about the number of passengers from each embark town (How to find the count of unique records for all the unique values in a column of a DataFrame?). The Series contains the names of the embark towns as indexes and the number of passengers as values.
We are then useing the pyplot.pie() function to plot the pie chart. The x parameter indicates the number of passengers from each embark town. The labels parameter labels the slices of the pie chart. In our case, the labels are the names of the embark towns. The autopct parameter indicates the format in which the percentage of passengers will be shown. And the explode parameter helps in plotting the pie chart with some spaces between the slices.
The resulting pie chart will look like the following:









































0 Comments