How to generate grouped PIE plot using Python

How to generate grouped PIE plot using Python

Creating a grouped pie chart in Python can be accomplished using the matplotlib library. The first step is to import the library and the necessary submodules for creating a pie chart.

import matplotlib.pyplot as plt
import numpy as np

Next, you’ll need to create the data that will be used to generate the chart. This data should be in the form of a list of lists, where each sublist represents a group of data. For example:

data = [[20, 30, 50], [40, 10, 50], [35, 45, 20]]

The example above represents three groups of data, each with three values.

Once you have your data, you can create the chart using the following code:

// create the chart
fig, ax = plt.subplots()
ax.axis('equal')


// Create pie charts
pie1 = ax.pie(data[0], labels=['A', 'B', 'C'], autopct='%1.1f%%')
pie2 = ax.pie(data[1], labels=['D', 'E', 'F'], autopct='%1.1f%%', labeldistance=0.6, radius=0.6, startangle=90)
pie3 = ax.pie(data[2], labels=['G', 'H', 'I'], autopct='%1.1f%%', labeldistance=0.8, radius=0.8)


// Add legend
plt.legend(title='Groups', bbox_to_anchor=(1, 0.5))


// Show the chart
plt.show()

In this example, the “autopct” parameter is used to format the values displayed within each slice of the pie chart. The “labels” parameter is used to specify the label for each value, and the “labeldistance” parameter is used to control the distance of the labels from the center of the chart. The radius parameter controls the radius of each group’s pie. Additionally, you can add legend by passing title and the bbox_to_anchor(bounding box to anchor) parameter.

With this code, you should now have a grouped pie chart that displays the data you specified. You can customize the appearance of the chart further by using other options available in the matplotlib library.

You can also use other libraries like seaborn or plotly, as they also provide functionality for grouped pie chart in an efficient way.

In this Learn through Codes example, you will learn: How to generate grouped PIE plot using Python.



Essential Gigs