A pie chart is a common type of chart used in data visualization. Pie charts are used to display categorical data, and they are particularly useful when the number of categories is small. In this article, we will explore how to create a pie chart using Python and the Pandas library.
Pandas is a popular data manipulation library in Python that provides many different options for working with data. One of these options is the ability to create charts and graphs directly from data using the DataFrame.plot() method. This method provides several different kinds of charts and graphs, including pie charts.
Creating a Pie Chart in Python Using Pandas
To create a pie chart using Pandas, we first need to import the necessary libraries. We will be using the Pandas and Matplotlib libraries for this tutorial. The code to import these libraries looks like this:
import pandas as pd
import matplotlib.pyplot as plt
Next, let's create a simple dataset to use for our chart. In this example, we will use a list of pizza orders:
pizza_orders = {
'Cheese': 15,
'Pepperoni': 20,
'Vegetarian': 5,
'Hawaiian': 10
}
This dataset contains four categories of pizza orders and the number of orders for each category. To create a pie chart from this data, we need to convert it into a Pandas DataFrame. Here's how we do that:
df = pd.DataFrame(pizza_orders.items(), columns=['Pizza', 'Orders'])
In the code above, we convert the pizza_orders dictionary to a list of tuples using the items() method and then convert that list to a DataFrame. We also specify the column names using the columns attribute of the DataFrame constructor.
Now that we have our data in a DataFrame, we can use the plot.pie() method to create a pie chart. Here's what the code looks like:
df.plot.pie(y='Orders', labels=df['Pizza'], autopct='%1.1f%%', startangle=90)
plt.axis('equal')
plt.show()
In the code above, we specify the y-axis using the 'Orders' column of our DataFrame and the labels using the 'Pizza' column. We also specify the autopct parameter to format the percentages displayed on each slice of the pie chart. Finally, we set the start angle to 90 degrees, which rotates the chart so that the first slice starts at the top.
The result of running this code is a pie chart that displays our pizza order data. Each slice represents a category of pizza, and the size of the slice represents the percentage of orders for that category.
Here's what our pie chart looks like:
Customizing a Pie Chart in Python
There are several ways to customize a pie chart in Python. For example, we can change the colors of the slices, add a title, and adjust the layout of the chart.
Let's add a title to our pizza order chart. We can do this using the title() method of the pyplot module:
plt.title('Pizza Orders')
We can also change the colors of the slices using the colors parameter:
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']
df.plot.pie(y='Orders', labels=df['Pizza'], autopct='%1.1f%%', startangle=90, colors=colors)
In the code above, we specify a list of colors for each slice of the pie chart. Finally, we can adjust the layout of the chart using the subplots_adjust() method:
plt.subplots_adjust(left=0.0, bottom=0.1, right=0.95, top=0.9)
This code adjusts the margins of the chart to make it fit better within the window.
Pie charts are a great way to visualize categorical data, and with Pandas, it's easy to create them within Python. By customizing the chart's title, colors, and layout, we can create a chart that effectively communicates our data to others.
Conclusion
Pie charts are a useful tool for displaying categorical data in a clear and concise way. With Pandas and Python, it's easy to create these charts directly from data. By customizing the chart's features, we can create a chart that effectively communicates our data to others.
In this article, we explored how to create a pie chart using Pandas and Python and demonstrated how to customize various aspects of the chart using code examples. We have discussed how to make a simple dataset, plotting and customizing the pie chart.
Creating a Pie Chart in Python Using Pandas
To give you a better understanding of how to create a pie chart using Pandas, let's break down the code used in the example we provided earlier:
pizza_orders = {
'Cheese': 15,
'Pepperoni': 20,
'Vegetarian': 5,
'Hawaiian': 10
}
df = pd.DataFrame(pizza_orders.items(), columns=['Pizza', 'Orders'])
df.plot.pie(y='Orders', labels=df['Pizza'], autopct='%1.1f%%', startangle=90)
plt.axis('equal')
plt.show()
The first section of the code initializes a dictionary called pizza_orders
that contains the categories of pizza we want to plot as keys and the number of orders for each category as values.
Next, we use the pd.DataFrame()
method from Pandas to create a DataFrame object from our pizza_orders
dictionary. This method converts a dictionary to a dataframe object. We pass two parameters to this method: pizza_orders.items()
, which returns a list of tuples with our pizza categories and their corresponding values, and columns=['Pizza', 'Orders']
, which labels each column in our DataFrame.
The DataFrame.plot()
method is used to generate a pie chart from our data. We specify the 'Orders'
column in our DataFrame as the y-axis and the 'Pizza'
column as the labels for each slice of the pie chart. We also use the autopct
parameter to display the percentage of orders per pizza category. Finally, we set the startangle
parameter to 90 to ensure that the first slice of the pie chart starts at the top.
Finally, we use the axis()
method to set the aspect ratio of the chart to equal, and the show()
method to display the chart.
Customizing a Pie Chart in Python
As we mentioned earlier, there are several ways to customize a pie chart in Python. In the following sections, we will discuss a few common customizations.
Changing the Colors of the Slices
The simplest way to customize a pie chart is to change the colors of the slices. We can do this by passing a list of colors to the colors
parameter of the df.plot.pie()
method.
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
df.plot.pie(y='Orders', labels=df['Pizza'], autopct='%1.1f%%', startangle=90, colors=colors)
In the code above, we create a list of colors and pass it to the colors
parameter. Each color in the list corresponds to a slice in the pie chart.
Adding a Title to the Chart
A common way to add context to a chart is to give it a title. We can add a title to our pie chart using the title()
method of the pyplot
module:
plt.title('Pizza Orders')
This code adds the string 'Pizza Orders' as the title of our chart.
Adjusting the Layout of the Chart
By default, Pandas generates a pie chart with tight margins. We can use the subplots_adjust()
method of the pyplot
module to adjust the margins of the chart:
plt.subplots_adjust(left=0.0, bottom=0.1, right=0.95, top=0.9)
In the code above, we adjust the left, bottom, right, and top margins of the chart using four parameters to the subplots_adjust()
method. These parameters specify the position of the subplot as a fraction of the figure width or height. The values we used in this example are the default values that produce a reasonable layout.
Conclusion
In this article, we introduced you to creating a pie chart using Python and Pandas. We have also discussed the different ways to customize a pie chart in Python, such as changing the colors of the slices, adding a title, and adjusting the layout of the chart.
Whether you are a data analyst, data scientist, or software engineer, understanding data visualization is an essential skill in today's world. By mastering Python and its data visualization libraries such as Pandas, you can create beautiful and effective data visualizations to communicate your data insights to others.
Popular questions
-
What is a pie chart, and what is it used for?
A pie chart is a type of chart used in data visualization to display categorical data. It is useful when you want to show the proportion of each item in a dataset. -
How do you create a pie chart using Python and Pandas?
You can create a pie chart using theplot.pie()
method of a Pandas DataFrame object. You need to specify the column containing the values to plot, the labels for each slice, and other options such as start angle and autopct. -
Can you customize the appearance of a pie chart in Python?
Yes, you can customize the appearance of a pie chart in Python using various options. For example, you can change the colors of the slices, add a title, or adjust the layout of the chart. -
What is the purpose of the
autopct
parameter in a pie chart?
Theautopct
parameter in a pie chart is used to display the percentage of each slice of the pie chart. You can use various formatting options to control how the percentage is displayed. -
Is Pandas the only library available for creating pie charts in Python?
No, there are several libraries available for creating pie charts in Python, including Matplotlib, Seaborn, and Plotly. However, Pandas is a popular choice because it integrates with other data manipulation functions in Pandas.
Tag
PandasPieChart.