2011-01-26 253 views
54

有人能解釋爲什麼下面的代碼在設置圖形的facecolor時不起作用嗎?Matplotlib figure facecolor(背景顏色)

import matplotlib.pyplot as plt 

# create figure instance 
fig1 = plt.figure(1) 
fig1.set_figheight(11) 
fig1.set_figwidth(8.5) 

rect = fig1.patch 
rect.set_facecolor('red') # works with plt.show(). 
          # Does not work with plt.savefig("trial_fig.png") 

ax = fig1.add_subplot(1,1,1) 

x = 1, 2, 3 
y = 1, 4, 9 
ax.plot(x, y) 

# plt.show() # Will show red face color set above using rect.set_facecolor('red') 

plt.savefig("trial_fig.png") # The saved trial_fig.png DOES NOT have the red facecolor. 

# plt.savefig("trial_fig.png", facecolor='red') # Here the facecolor is red. 

當我指定使用fig1.set_figheight(11)fig1.set_figwidth(8.5)這些由命令plt.savefig("trial_fig.png")拿起該圖的高度和寬度。但是,facecolor設置未被拾取。爲什麼?

感謝您的幫助。

回答

75

這是因爲savefig覆蓋了圖形背景的facecolor。

(這是故意的,居然......的假設是,你可能想要控制所保存的數字與facecolor kwarg到savefig的背景色。這是一個混亂和不一致的默認,但!)

最簡單的解決方法就是做fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none')(我指定這裏的edgecolor因爲實際數字默認edgecolor是白色的,它會給你一個白色邊框保存圖)

希望幫助!

+0

感謝您的解釋! – Curious2learn 2011-01-26 19:29:49

17

我只好用透明的關鍵字,以得到我選擇的顏色與我最初的

fig=figure(facecolor='black') 

這樣的:

savefig('figname.png', facecolor=fig.get_facecolor(), transparent=True) 
10

savefigfacecolor自己的參數。 我覺得比接受的答案更簡單的方法是將它們設置全局只是一次,而不是每次都放facecolor=fig.get_facecolor()

plt.rcParams['axes.facecolor']='red' 
plt.rcParams['savefig.facecolor']='red'