pythonmatplotlibpie-charttexplot-annotations

Pie Chart Mathtext Label/Autopct


So I've been fooling around with the pyplot pie() function and it works well and all except for when I try to use mathtext in the wedge labeling (as in the autopct labeling, where I'd like the number, a \pm (+-) sign and some relevant number). Is it possible to do this simply? Would I have to pull out all the wedge objects and manipulate their text (perhaps itself being a series of Text objects) or is there some simpler way? I don't mind some complexity, I'd just really like to be able to do this.

edit: an example would be the first pie chart example in the matplotlib code gallery:

import matplotlib.pyplot as plt


# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')

plt.show()

The idea would be to have the numbers generated by the autopct format keyword ended with a +- and some number.


Solution

  • I'm not sure to understand if your problem is with mathtext or just with creating a custom label. In addition you don't say where you get the value that you want to put after the ± sign.

    Here I assume you have a list with the value you want to add for each wedge.

    # The slices will be ordered and plotted counter-clockwise.
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    sizes = [15, 30, 45, 10]
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
    explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
    
    patches, texts, autotexts = plt.pie(sizes, explode=explode, labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=True, startangle=90)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')
    
    
    otherInfo = [3, 5, 3, 4]
    
    for text, info in zip(autotexts, otherInfo):
        text.set_text(u"%s ± %.1f" % (text.get_text(), info)) #you can play here with the format to get the label that you want
    

    enter image description here