Python 如何使用 Matplotlib 设置图形背景颜色的不透明度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4581504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:25:27  来源:igfitidea点击:

How to set opacity of background colour of graph wit Matplotlib

pythonmatplotlibalpha

提问by

I've been playing around with Matplotlib and I can't figure out how to change the background colour of the graph, or how to make the background completely transparent.

我一直在玩 Matplotlib,但我不知道如何更改图形的背景颜色,或者如何使背景完全透明。

采纳答案by Joe Kington

If you just want the entire background for both the figure and the axes to be transparent, you can simply specify transparent=Truewhen saving the figure with fig.savefig.

如果您只希望图形和轴的整个背景都是透明的,则可以transparent=True在保存图形时使用fig.savefig.

e.g.:

例如:

import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', transparent=True)

If you want more fine-grained control, you can simply set the facecolor and/or alpha values for the figure and axes background patch. (To make a patch completely transparent, we can either set the alpha to 0, or set the facecolor to 'none'(as a string, not the object None!))

如果您想要更细粒度的控制,您可以简单地为图形和轴背景补丁设置 facecolor 和/或 alpha 值。(要使补丁完全透明,我们可以将 alpha 设置为 0,或将 facecolor 设置为'none'(作为字符串,而不是对象None!))

e.g.:

例如:

import matplotlib.pyplot as plt

fig = plt.figure()

fig.patch.set_facecolor('blue')
fig.patch.set_alpha(0.7)

ax = fig.add_subplot(111)

ax.plot(range(10))

ax.patch.set_facecolor('red')
ax.patch.set_alpha(0.5)

# If we don't specify the edgecolor and facecolor for the figure when
# saving with savefig, it will override the value we set earlier!
fig.savefig('temp.png', facecolor=fig.get_facecolor(), edgecolor='none')

plt.show()

alt text

替代文字