Python matplotlib Pie Chart

The Python matplotlib pie chart displays the series of data in slices or wedges, and each slice is the size of an item. In order to draw at the matplotlib chart in Python, you have to use the pyplot pie function. The syntax of this Python matplotlib pie function is

matplotlib.pyplot.pie(x, labels = None)

Apart from the above, there are many arguments that you can use to style the Python matplotlib pie chart. In this chapter, we cover most of those matplotlib pie function arguments with a practical example.

Python matplotlib Pie Chart Example

In this Python pie chart example, we declared two lists X and Y, where X represents a few programming languages, and y represents some random values. Next, we used the matplotlib pie function to draw a chart.

from matplotlib import pyplot as plt

x = [22, 9, 40, 27, 55]
y = ['C', 'C++', 'Java', 'Python', 'JavaScript']

plt.pie(x, labels = y)
plt.show()
Python matplotlib Pie Chart 1

It is an example of a Python pie chart using a CSV file. Here, we are using the global sales data and drawing the chart that represents the Sales by Order Priority.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()
print(sales_data)

plt.pie(sales_data['Sales'], labels = sales_data.index)

plt.show()
Pyplot Pie plot 2

Add Title or Name to Pie Plot

The Python matplotlib pyplot has a title method, which helps to assign a title or heading for the pie chart. Here, we assigned a new title to this and formatted that title font style, color, and weight.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()

plt.pie(sales_data['Sales'], labels = sales_data.index)

plt.title("Sales Percentage by Order Priority",
     color = 'blue', fontweight = 'bold', fontsize = '20')

plt.show()
Add Title to Pie Plot 3

Change matplotlib Pie chart colors

By default, the Python pie function uses the active colors in a current cycle to plot chart. However, you can use the Python colors argument to assign your own colors to each wedge. For instance, here, we are assigning cyan, green, yellow, and maroon colors to those four pies.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()
print(sales_data)

colors_list = ['cyan', 'green', 'yellow', 'Maroon']

plt.pie(sales_data['Sales'], labels = sales_data.index, colors = colors_list)

plt.show()
Change Default Colors of each pyplot Pie 4

matplotlib Pie chart Percentage

The autopct argument shows the percentage of each slice in a matplotlib pie chart. Here, you can use the string format to vary the display of percentage values. For example, %1.2f%% returns value 25.34%, and .1f% returns 25.3%.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()

colors_list = ['cyan', 'yellowgreen', 'orange', 'Maroon']

plt.pie(sales_data['Sales'], labels = sales_data.index,
    autopct = '%1.1f%%', colors = colors_list)

plt.show()
Add Data Labels or Percentages to each Pyplot Pie 5

matplotlib Pie chart Slice out

The explode argument in pyplot decides which part should explode (separate and move a distance from the center). This argument accepts a tuple of numeric values, and each non-zero value represents the distance of that slice from the center. In this example, we exploded medium priority from the center.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()

colors_list = ['cyan', 'yellowgreen', 'orange', 'Maroon']

explode_val = (0, 0, 0, 0.1)

plt.pie(sales_data['Sales'], labels = sales_data.index,
    autopct = '%1.1f%%', explode = explode_val, colors = colors_list)

plt.show()
Python matplotlib Pie Chart Slice Out Example 6

It is another example of the explode. Here, we are exploding multiple wedges or slices. It might look odd, but you get the point.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()

colors_list = ['cyan', 'yellowgreen', 'orange', 'Maroon']

explode_val = (0, 0.4, 0, 0.1)

plt.pie(sales_data['Sales'], labels = sales_data.index,
    autopct = '%1.1f%%', explode = explode_val, colors = colors_list)

plt.show()
Python matplotlib Pie Chart Explode out 7

Rotating Python matplotlib pie chart

The startangle argument in this function allows choosing the chart starting position. It means you can rotate it based on the angle of degrees you provided. In this example, we are using 90 degrees so that the chart start position will start at 90 degrees. Next, we used the shadow argument and assigned True value to it (by default, it is false). It means matplotlib will draw a shadow beneath the chart.

There is one more argument called counterclock, and its default value is True. It means the plot will draw in counterclockwise. However, you can change the same by assigning False to this argument counterclock = False.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()

colors_list = ['cyan', 'yellowgreen', 'orange', 'Maroon']

explode_val = (0, 0.4, 0, 0)

plt.pie(sales_data['Sales'], labels = sales_data.index,
    autopct = '%1.1f%%', explode = explode_val,
    colors = colors_list,
    shadow = True,
    startangle = 90,
    counterclock = False)

plt.show()
Rotating Python matplotlib Pie Chart and Slice Out 8

Format Pie Plot labels

The Python matplotlib pie chart rotatelabels arguments accept the boolean value, and its default value is False. If you specify true, then each label in it will be rotated to the corresponding slice angle. Next, the labeldistance argument accepts the float value. Here, you can specify the distance of the label from the actual chart or slice. In this example, we specified 1.2 as the distance, and you can notice the same in the output.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()

colors_list = ['cyan', 'yellowgreen', 'orange', 'Maroon']

plt.pie(sales_data['Sales'], labels = sales_data.index,
    autopct = '%1.1f%%',
    colors = colors_list,
    labeldistance = 1.2,
    rotatelabels = True )

plt.show()
Format Data Labels and Region Names of a Python matplotlib Pie Chart 9

The wedgeprops argument is an optional arg, it accepts the dictionary values, and the default value is None. However, you can use this argument to alter the wedge or slice properties of a Python pie chart. Next, the frame argument places the chart inside a frame or axis.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()

colors_list = ['cyan', 'yellowgreen', 'orange', 'Maroon']

fg, ax = plt.subplots()

ax.pie(sales_data['Sales'], labels = sales_data.index,
    autopct = '%1.1f%%',
    colors = colors_list,
    frame = True,
    wedgeprops = {'linewidth' : 4,
           'edgecolor' :'blue'}
    )

ax.axis('equal')
plt.show()
Add Border Lines and Colors to Python matplotlib Pie Chart 10

Add Legend to Pie Plot

The legend function allows providing the labels in legend form. Within the function, use a loc argument to place the legend in a required position. In this Python matplotlib pie chart example, we are putting it in an upper right corner.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()

colors_list = ['cyan', 'yellowgreen', 'orange', 'Maroon']

fg, ax = plt.subplots()

ax.pie(sales_data['Sales'],
    autopct = '%1.1f%%',
    colors = colors_list,
    frame = True
    )

ax.legend(sales_data.index, loc = 'upper right')
   
ax.axis('equal')
plt.show()
Add Legend to Python matplotlib Pie Chart 11

We forgot to mention the ax.axis(‘equal’) in all our previous examples. It will make sure the Python pyplot pie chart rounded. Sometimes, your chart might look oval and overcome the issue you have use this.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_excel('/Users/suresh/Downloads/Global_Superstore.xls')

sales_data = df.groupby('Order Priority')[['Sales']].sum()

colors_list = ['cyan', 'yellowgreen', 'orange', 'Maroon']

explode_val = (0, 0.4, 0, 0.1)

fg, ax = plt.subplots()

ax.pie(sales_data['Sales'],
    autopct = '%1.2f%%',
    explode = explode_val,
    colors = colors_list,
    frame = True,
    shadow = True,
    startangle = 90,
    counterclock = False,
    wedgeprops = {'linewidth' : 4,
           'edgecolor' :'blue'}
    )
ax.legend(sales_data.index, loc = 'upper left')
ax.axis('equal')

plt.title("Sales Percentage by Order Priority",
     color = 'green', fontweight = 'bold', fontsize = '20')
plt.show()
Python matplotlib Pie Chart rounded with legend 12