如何使用 Matplotlib 设置图形背景颜色的不透明度
我一直在使用 Matplotlib,但不知道如何更改图形的背景颜色,或者如何使背景完全透明。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只希望图形和轴的整个背景都是透明的,则只需在使用
fig.savefig
保存图形时指定transparent=True
即可。例如:
如果您想要更细粒度的控制,您可以简单地设置图形和轴背景补丁的面部颜色和/或 alpha 值。 (要使补丁完全透明,我们可以将 alpha 设置为 0,或者将面颜色设置为
'none'
(作为字符串,而不是对象None
!) )例如:
If you just want the entire background for both the figure and the axes to be transparent, you can simply specify
transparent=True
when saving the figure withfig.savefig
.e.g.:
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 objectNone
!))e.g.:
另一种方法是设置适当的全局
rcParams
并简单地指定颜色。这是一个 MWE(我使用 RGBA 颜色格式来指定 alpha/不透明度):figure.facecolor 是主要背景颜色,axes.facecolor 是背景颜色实际情节。无论出于何种原因,
plt.savefig
使用savefig.facecolor
作为主要背景颜色而不是figure.facecolor
,因此请务必更改此参数因此。上面代码中的
plt.show()
会产生以下输出:和
plt.savefig("temp.png")
结果如下输出:如果你想让某些东西完全透明,只需将相应颜色的alpha值设置为0即可。对于
plt.savefig
,还有一个“lazy”选项通过将 rc 参数savefig.transparent
设置为True
,这会将所有面部颜色的 alpha 设置为 0%。请注意,更改
rcParams
具有 <强>全局效应,因此请记住,您的所有绘图都会受到这些变化的影响。但是,如果您有多个绘图,或者您想要更改无法更改源代码的绘图的外观,则此解决方案可能非常有用。Another way is to set the appropriate global
rcParams
and simply specify the colors. Here is an MWE (I used the RGBA color format to specify the alpha/opacity):The
figure.facecolor
is the main background color and theaxes.facecolor
the background color of the actual plot. For whatever reason,plt.savefig
usessavefig.facecolor
as the main background color rather thanfigure.facecolor
, so make sure to change this parameter accordingly.plt.show()
from the code above results in the following output:and
plt.savefig("temp.png")
results in this output:If you want to make something completely transparent, simply set the alpha value of the corresponding color to 0. For
plt.savefig
, there is also a "lazy" option by setting the rc-parametersavefig.transparent
toTrue
, which sets the alpha of all facecolors to 0%.Note that altering the
rcParams
has a global effect, so bear in mind that all your plots will be affected by these changes. However, this solution can be extremely useful if you have multiple plots, or if you want to change the appearance of plots where you cannot change the source code.