Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Python Pandas - Pie Plot



A pie plot is a circular chart that shows data as slices, with each slice representing a portion of the dataset. It is useful for visualizing the relative sizes of different data values. In a pie chart, the size of each slice, including its angle, area, and arc length, corresponds to the value or percentage it represents. The total of all percentages equals 100%, and the sum of all slice angles is 360.

For instance, consider a dataset that records the pass percentages of boys and girls in a classroom. A pie plot visually represents this data, where each slice indicates the proportion of boys and girls passing.

Pie Plot Introduction

In this tutorial, we will learn how to create and customize pie plots in Python using the Pandas library.

Pie Plot in Pandas

In Pandas, pie plot can be created using theplot.pie() method for both the Series and DataFrames objects. This method internally use Matplotlib and return either amatplotlib.axes.Axes object or NumPy arraynp.ndarray of Axes when subplots parameter is set to True.

  • DataFrame.plot.pie(): Creates pie plot for one or more columns in a DataFrame.

  • Series.plot.pie(): Creates a pie plot for a specific column or Series.

Syntax

Following is the syntax of the plot.pie() method for both the Series and DataFrames objects −

Series.plot.pie(**kwargs)

Where,

  • y: Specify the column label or position to plot. Required when usingDataFrame.plot.pie() without subplots=True.

  • **kwargs: Additional keyword arguments to customize the plot appearance.

Example: Creating Pie Plot for Series Data

This example demonstrates using theSeries.plot.pie() method on a pandas Series object to generate the pie plot.

import pandas as pdimport numpy as npimport matplotlib.pyplot as plt# Create a Pandas Seriesseries = pd.Series(3 * np.random.rand(4), index=["a", "b", "c", "d"])# Generate a pie plotseries.plot.pie(figsize=(7, 4))# Set title and Display the plotplt.title('Basic Pie Plot')plt.show()

Following is the output of the above code −

Basic Pie Plot

Example: Creating Pie Plot for a DataFrame

This example uses theDataFrame.plot.pie() method for the creating the pie plot.

import pandas as pdimport matplotlib.pyplot as plt# Create a DataFrame with pass percentagesdata = {"Category": ["Boys", "Girls"], "Pass Percentage": [75, 85]}df = pd.DataFrame(data)# Plotting the pie chartdf.plot.pie(y="Pass Percentage", labels=df["Category"], figsize=(7, 4))# Set title and Display the plotplt.title('Pie Plot for DataFrame')plt.show()

After executing the above code, we get the following output −

Pie Plot for DataFrame

Customizing a Pie Plot

Pandas allows customization of pie plots through various parameters such as, labels, colors, autopct, fontsize, and more.

Example

This example demonstrates customizing the pie plot using the addition keyword arguments.

import pandas as pdimport matplotlib.pyplot as plt# Create a DataFrame with pass percentagesdata = {    "Category": ["Boys", "Girls"],    "Pass Percentage": [75, 85]}df = pd.DataFrame(data)# Plotting the pie chartdf.plot.pie(y="Pass Percentage", labels=df["Category"], autopct="%.1f%%", colors=["skyblue", "pink"], figsize=(7, 4))# Set title and plt.title('Customizing a Pie Plot')plt.show()

Following is the output of the above code −

Customizing a Pie Plot

Pie Plots for All DataFrame Columns

When plotting a pie plot from a DataFrame, you must specify a column using they parameter or usesubplots=True to plot multiple pie charts for all numerical columns.

Example

This example demonstrates creating pie plot for all DataFrame columns in a multiple subplots.

import pandas as pdimport matplotlib.pyplot as pltimport numpy as np# Create a DataFrame df = pd.DataFrame(3 * np.random.rand(4, 2), index=["a", "b", "c", "d"], columns=["Column1", "Column2"])# Plotting the pie chartdf.plot.pie(subplots=True, autopct="%.1f%%", figsize=(7, 4), title='Pie Plots for All Columns')# Display the Plotplt.show()

Following is the output of the above code −

Pie Plots for All Columns

Pie Plot Handling NaN Values

Pandasplot.pie() method easily handles the missing values (NaN), if your data contains any. The method automatically fills the missing data with 0 when creating a pie plot.

Example

The following example shows how theplot.pie() method handles the missing values.

import pandas as pdimport numpy as npimport matplotlib.pyplot as plt# Create a Pandas Seriesseries = pd.Series([1, 2, np.nan, 4], index=["A", "B", "C", "D"])# Generate a pie plotseries.plot.pie(figsize=(7, 4))# Set title and Display the plotplt.title('Pie Plot Handling Missing Values')plt.show()

On executing the above code we will get the following output −

Pie Plot Handling Missing Values
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp