matplotlib examples‎ > ‎Posts‎ > ‎

stacked bar plot with legend (hatch pattern), exploded pie chart

posted May 17, 2011, 11:35 PM by Mart Objartel   [ updated Oct 26, 2011, 10:00 AM ]
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(7.4, 7.4))


ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

#data
data_1 = [3, 4, 1, 5, 7]


#pie plot explosion data
expl = [0.1, 0.1, 0.1, 0.1, 0.25]

#calculate the sum of data points
Sum = np.sum(data_1)

#labels data
text_1 = ["proteins", "carbs", "fats", "oils", "minerals"]

#http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.patches.Patch.set_hatch
def Hatcher(imp):
    if imp == "proteins":
        out = "//"
    elif imp == "carbs":
        out = "--"
    elif imp == "fats":
        out = "xx"
    elif imp == "oils":
        out = "\\"
    else:
        out = "++"

    return out

lefter = 0

#horizontal bar plot
for i in np.arange(0, len(data_1)):
   
    ax1.barh([1], data_1[i],  1,left=lefter, hatch=Hatcher(text_1[i]), color="w", label="%s" % (text_1[i]))
    #add % labels to bars
    ax1.text(lefter+(data_1[i]/2), 1.5, "%s%s" % (data_1[i]*100/Sum, "%"), size=10, backgroundcolor="w")

    lefter += data_1[i]

#hide x ticks   
ax1.set_xticks([])

#asjust y axis
ax1.set_ylim(1,2)

#set y tick location
ax1.set_yticks([1.5])

#replace y tick with text string
ax1.set_yticklabels(["nutrients"])

ax1.set_title("Horizontal bar plot")

#generate legend and move  it off the plot, labels are defined in ax1.barh argument "label="
ax1.legend(bbox_to_anchor = (1.37, 0.8))

#simple pie plot
ax2.pie(data_1, labels=text_1, autopct='%1.0f%%', labeldistance=1.1, explode=expl)
ax2.set_title("Exploded pie plot")


plt.subplots_adjust(right=0.76)
plt.show()


ċ
barpie.py
(2k)
Mart Objartel,
May 18, 2011, 12:13 AM
Comments