How to Create a Pie Chart From a Dataframe in Python

To create a pie chart from a dataframe in Python, use the plt.pie() function from the matplotlib library.

The following example shows how to create a pie chart from a dataframe in Python using the plt.pie() function.

Using plt.pie() Function

The plt.pie() function allows you to generate pie charts directly from your DataFrame in Python.

Let’s consider a DataFrame that lists various office products and their corresponding prices. You can create a pie chart to represent the price distribution of these items.

# Import library
import pandas as pd
import matplotlib.pyplot as plt

# Load the data into a dataframe
office_stuff = pd.DataFrame({
    'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
    'Price': [4500, 550, 250, 50, 350, 50]
})

# Create a pie chart
plt.pie(office_stuff['Price'], labels=office_stuff['Product_Name'], autopct='%1.1f%%')
plt.title('Office Stuff Prices')
plt.show()

Output: 👇️

Pie Chart

In the above code, it creates a pie chart based on the office_stuff DataFrame, where the Price column values represent the size of the slices, and the Product_Name values provide labels for each slice.

The autopct parameter ensures that each slice displays its corresponding percentage in the chart.

  • plt.pie(): This function is used to generate the pie chart. The Price column values from the DataFrame are passed as data, and the Product_Name column provides the labels for the chart slices.
  • autopct='%1.1f%%': This formats the percentage label to show one decimal point, making it easier to read and interpret.
  • plt.title(): Adds a title to the pie chart, making the chart’s purpose clear.
  • plt.show(): Displays the pie chart in a pop-up window.

Conclusion

By using plt.pie() from matplotlib, you can quickly generate pie charts directly from a DataFrame in Python.