Python matplotlib 图例背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19863368/
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-19 14:49:52  来源:igfitidea点击:

matplotlib legend background color

pythonmatplotlib

提问by user1850133

Is there while rcParams['legend.frameon'] = 'False'a simple way to fill the legend area background with a given colour. More specifically I would like the grid not to be seen on the legend area because it disturbs the text reading.

有没有rcParams['legend.frameon'] = 'False'一种简单的方法可以用给定的颜色填充图例区域背景。更具体地说,我希望在图例区域不要看到网格,因为它会干扰文本阅读。

The keyword framealphasounds like what I need but it doesn't change anything.

关键字framealpha听起来像我需要的,但它不会改变任何东西。

import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['legend.frameon'] = 'False'
plt.plot(range(5), label = u"line")
plt.grid(True)
plt.legend(loc = best)
plt.show()

I've also tried:

我也试过:

legend = plt.legend(frameon = 1)
frame = legend.get_frame()
frame.set_color('white')

but then I need to ask how can I change the background colour while keeping the frame on? Sometimes I want it ON with a background colour other than white. And also, is there a way of changing the colour of the frame? With the above code I was expecting to change the colour of the frame only, not the background.

但是然后我需要问如何在保持框架打开的同时更改背景颜色?有时我希望它使用白色以外的背景颜色打开。而且,有没有办法改变框架的颜色?使用上面的代码,我希望只更改框架的颜色,而不是背景。

采纳答案by Molly

You can set the edge color and the face color separately like this:

您可以像这样分别设置边缘颜色和面部颜色:

frame.set_facecolor('green')
frame.set_edgecolor('red')

There's more information under FancyBboxPatch here.

还有FancyBboxPatch下更多的信息在这里

回答by spinup

In addition to Molly's method you can turn the frame off using the linewidth:

除了Molly的方法之外,您还可以使用 linewidth 关闭框架:

frame.set_linewidth(0)

I used that method in a small convenience function I wrote to hide the legend frames for the same reason you cite. The function is called adjust_legendsin the print_targeted_plotsmodule available from github.

出于与您引用的相同的原因,我在编写的一个小型便利函数中使用了该方法来隐藏图例框架。该函数adjust_legendsgithubprint_targeted_plots提供的模块中调用。

回答by oveoyas

Using matplotlib.pyplot, plt.legend(facecolor='white', framealpha=1)will give your legend a white background without transparency.

使用 matplotlib.pyplot,plt.legend(facecolor='white', framealpha=1)会给你的图例一个没有透明度的白色背景。