前面的问题涉及到使用savefig()以与屏幕上显示的相同的面颜色(背景色)保存,即:
fig = plt.figure()
fig.patch.set_facecolor('blue')
fig.savefig('foo.png', facecolor=fig.get_facecolor())Matplotlib figure facecolor (background color)
(使用savefig()需要我们重新指定背景颜色。)
我还可以为透明度指定一个alpha,例如:How to set opacity of background colour of graph wit Matplotlib
fig.patch.set_alpha(0.5)
我找不到一种方法来使图形具有透明的面部颜色保存,因为它显示在屏幕上。文档似乎不完整:http://matplotlib.org/faq/howto_faq.html#save-transparent-figures -没有显示实际节省的金额。将transparent=True与savefig()一起使用并不具有使面部颜色透明的预期效果,相反,它似乎使该颜色(包括图形背景)上除轴图例之外的所有内容都透明。
编辑:一些相关的代码摘录:
def set_face_color(fig, facecolor):
if facecolor is False:
# Not all graphs get color-coding
facecolor = fig.get_facecolor()
alpha = 1
else:
alpha = 0.5
color_with_alpha = colorConverter.to_rgba(
facecolor, alpha)
fig.patch.set_facecolor(color_with_alpha)
def save_and_show(plt, fig, save, disp_on, save_as):
if save:
plt.savefig(save_as, dpi=dpi_file, facecolor=fig.get_facecolor(),
edgecolor='none')
if disp_on is True:
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
plt.show()
else:
plt.close('all')也许可以将它们组合在一起,但我经常在构建子图网格之前,在绘图函数的开头调用set_face_color(),然后在末尾调用save_and_show()。我猜它应该在这两个地方都能工作,但我更喜欢保持函数的分离,并能够从最终的图中提取要传递给savefig()的alpha。
编辑2-千言万语
左侧的Alpha = 0.5,右侧的1。

t = [1, 2, 3, 4, 5]
fig = plt.figure()
fig.patch.set_alpha(0.5)
fig.set_facecolor('b')
plt.plot(t, t)
fig2 = plt.figure()
fig2.set_facecolor('b')
plt.plot(t,t)发布于 2016-07-19 11:16:03
我在Matplotlib 1.5上运行了你的代码,发现它为我产生了预期的输出。对于将来在这方面发生的所有事情,我在下面给出两个简单的方法来实现这一点。
快速注意,您绝对不希望将transparent=True设置为savefig的选项,因为这将覆盖您在matplotlib.figure.savefig source中看到的facecolors。
为了真正解决你的问题,你发布的第二个链接How to set opacity of background colour of graph wit Matplotlib实际上解决了这个问题。问题中的代码片段的问题是使用fig.set_facecolor而不是fig.patch.set_facecolor
解决方法1:
从上面链接的问题中,使用facecolor参数保存
import matplotlib.pyplot as plt
fig = plt.figure()
fig.patch.set_facecolor('b') # instead of fig.patch.set_facecolor
fig.patch.set_alpha(0.5)
plt.plot([1,3], [1,3])
plt.tight_layout()
plt.show()
plt.savefig('method1.png', facecolor=fig.get_facecolor())解决方法2:
您还可以通过rcParams指定savefig facecolor。
import matplotlib.pyplot as plt
import matplotlib as mpl
fig = plt.figure()
col = 'blue'
#specify color of plot when showing in program.
#fig.set_facecolor(col) also works
fig.patch.set_facecolor(col)
#specify color of background in saved figure
mpl.rcParams['savefig.facecolor'] = col
#set the alpha for both plot in program and saved image
fig.patch.set_alpha(0.5)
plt.plot([1,3], [1,3])
plt.tight_layout()
plt.show()
plt.savefig('method2.png')如果你想让你的轴有一个背景,这些解决方案应该保持背景(比如Erotemic注释中的seaborn产生的)不变。如果您想更明确地说明这一点,请添加:
ax.patch.set_color('palegoldenrod') # or whatever color you like
ax.patch.set_alpha(.7)轴补丁alpha将不需要额外的工作就会转移到savefig。
请注意,在这两种情况下,我都使用了plt.tight_layout()来消除保存的图形中无用的额外空间。您可以在matplotlib documentation中了解更多信息。
https://stackoverflow.com/questions/24542610
复制相似问题