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 pie 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 pie chart.

# Python matplotlib Pie Chart Examples

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 pie 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()
Python matplotlib Pie Chart 2

Python pie Chart title

The Python 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 matplotlib pie chart 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()
Python matplotlib Pie Chart 3

Change matplotlib Pie chart colors

By default, the Python pie function uses the active colors in a current cycle to plot pie chart. However, you can use the Python colors argument to assign your own colors to each pie or 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()
Python matplotlib Pie Chart 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()
Python matplotlib Pie Chart 5

matplotlib Pie chart Slice out

The explode argument in pyplot pie 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 of a pie chart. In this Python pie chart 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 6

It is another example of the pie chart explode. Here, we are exploding multiple wedges or slices in a pie chart. 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 7

Rotating Python pie chart

The startangle argument in the pie function allows choosing the pie chart starting position. It means you can rotate the pie chart based on the angle of degrees you provided. In this example, we are using 90 degrees so that the pie 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 pie chart.

There is one more argument called counterclock, and its default value is True. It means the pie chart 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()
Python matplotlib Pie Chart 8

Format pie chart labels

The rotatelabels arguments accept the boolean value, and its default value is False. If you specify True, then each label in the pie chart 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 pie 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()
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 pie 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()
Python matplotlib Pie Chart 10

Matplotlib pie chart legend

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()
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 pie 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 12