0

I am using matplotlib to plot a pie chart. I have added a legend to the chart. However, i would like to add a "Total" to the legend, to sum up the values of all the other categories. Hence the value of "Total" would not be a part of the pie chart, and would only be shown in the legend. Is it possible for me to do that? Thank you.

miloovann
  • 21
  • 6
  • https://matplotlib.org/tutorials/intermediate/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artists – DavidG Jul 22 '20 at 08:10
  • Does this answer your question? [Manually add legend Items Python matplotlib](https://stackoverflow.com/questions/39500265/manually-add-legend-items-python-matplotlib) – DavidG Jul 22 '20 at 08:10

1 Answers1

0

You can create 2 legends. On the second one, you can create/manipulate symbol/text/title as you want. Here is a runnable code that you can try.

from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.pie(students, labels = langs,autopct='%1.2f%%')

# first legend
lgn = plt.legend()
ax = plt.gca().add_artist(lgn)

# second legend
gold_patch = mpatches.Patch(color='gold', label='Total= 9999')  # use your description text here
second_legend = plt.legend(handles=[gold_patch], loc=1, \
                           bbox_to_anchor=(0.5, 0.35, 0.55, 0.35)) # adjust location of legend here
second_legend.set_frame_on(False)  # use True/False as needed
second_legend.set_title("Other categories")

plt.show()

The output plot:

enter image description here

swatchai
  • 17,400
  • 3
  • 39
  • 58