How to add legend to matplotlib pie chart?

Using this example http://matplotlib.org/examples/pie_and_polar_charts/pie_demo_features.html how can I add a legend to this pie chart? My problem is that I have one large piece of 88.4%, the second largest cut is 10.6%, and the remaining slices are 0.7 and 0.3%. Labels around the pie are not displayed (except for the largest fragment) and no percentage values ​​for smaller fragments. Therefore, I can add a legend showing names and meanings. But I did not find out how ...

# -*- coding: UTF-8 -*- import matplotlib.pyplot as plt # The slices will be ordered and plotted counter-clockwise. labels = 'Rayos X', 'RMN en solución', 'Microscopía electrónica', 'Otros' sizes = [88.4, 10.6, 0.7, 0.3] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = (0.1, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, shadow=True, startangle=90) plt.legend(title="técnica") # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') plt.show() 
+5
matplotlib pie-chart legend
source share
1 answer

I checked your code, and plt.legend() creates the legend how you want it; perhaps set loc="lower left" so that it does not overlap with the corresponding pieces of the pie.

For me, the lines are displayed correctly, except for non-standard characters, which can lead to the fact that the problem will not be displayed to you at all. Only the largest slice and the "Growth" do not contain special characters. Perhaps try resizing the shapes as they can be pushed out of the canvas. Please refer to how to write accents with matplotlib and try again with the correct lines.

Interest is not displayed because you did not set it to show. Please refer to the example you posted as you missed autopct='%1.1f%%' , which will display percentages. In this special case, I would prefer not to make up the percentages, since they will overlap like marks on the border, as some slices are too small. Perhaps add this information to the legend.

Putting it all together (besides special characters - I had some problems with TeX activation), try the following code:

 # -*- coding: UTF-8 -*- import matplotlib.pyplot as plt # The slices will be ordered and plotted counter-clockwise. labels = [r'Rayos X (88.4 %)', r'RMN en solucion (10.6 %)', r'Microscopia electronica (0.7 %)', r'Otros (0.3 %)'] sizes = [88.4, 10.6, 0.7, 0.3] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] patches, texts = plt.pie(sizes, colors=colors, startangle=90) plt.legend(patches, labels, loc="best") # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') plt.tight_layout() plt.show() 

resulting pie chart

+11
source share

All Articles