首页 > 解决方案 > Save histogram of subplots to PDF

问题描述

I want to plot a histogram of 2 dictionaries: dict1 = {k1 : v} and dict2 = {k2 : v} where k1==k2.

The result is exactly what I want, but when I try to save it to pdf, I get an error 'tuple' object has no attribute 'savefig'. How can I save this histogram to pdf?

fig = plt.subplots(figsize =(40, 15))
barWidth = 0.25

EL= list(dict_graph_EL.values())
EA= list(dict_graph_EA.values())

#keys of dict_graph_EL == dict_graph_EA
br1 = np.arange(len(list(dict_graph_EL.keys()))) 
br2 = [x + barWidth for x in br1]

plt.bar(br1, EL, color ='blue', width = barWidth, edgecolor ='grey', label ='EL') 
plt.bar(br2, EA, color ='pink', width = barWidth, edgecolor ='grey', label ='EA') 

list_labels = list(dict_graph_EA.keys())
plt.xticks([r + barWidth for r in range(len(EL))], list_labels , rotation=60) 

plt.ylabel('Avg percentage of error on EL(blue)/EA(pink)')
plt.xlabel('Programs')

plt.legend(['Avg EL', 'Avg EA'], loc='upper left')

# Display the graph
plt.show(fig)

fig.savefig("avgELEA.pdf", bbox_inches='tight')

enter image description here

标签: pythonmatplotlib

解决方案


replace

fig = plt.subplots(figsize =(40, 15))

by

fig, ax = plt.subplots(figsize =(40, 15))

the function plt.subplots() is a convenient wrapper that creates both a figure and a set of subplots in one line. It returns a tuple (fig, axes) that needs to be unpacked as above if you want to use the reference to the figure for saving.


推荐阅读