Seaborn:带有背景颜色的图例

29
以下问题解释如何更改图例的背景颜色: matplotlib legend background color。但是,如果我使用seaborn,则此方法不起作用。有没有办法做到这一点?
import matplotlib.pyplot as plt
import numpy as np
a = np.random.rand(10,1)

plt.plot(a, label='label')
legend = plt.legend()
frame = legend.get_frame()
frame.set_facecolor('green')
plt.show()


import seaborn as sns

plt.plot(a, label='label')
legend = plt.legend()
frame = legend.get_frame()
frame.set_facecolor('green')
plt.show()

使用Matplotlib 使用Seaborn


请查看 add_legend 方法:https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py - xecafe
我不确定这怎么能帮到我 - 我没有 seaborn.axisgrid.Grid,而且轴上也没有 add_legend 方法。 - mathause
2个回答

47

默认情况下,seaborn会关闭图例的边框,如果您想自定义边框的外观,则需要在调用plt.legend时添加frameon=True


3
如果实际上没有边框,但frame = legend.get_frame()仍然返回某些东西,这仍然很奇怪。 - mathause

13

set_style()方法可以接受样式参数(例如'white''whitegrid''darkgrid'等)和一个字典参数,来覆盖默认的美学效果,包括是否有图例框。

如果您想要更改其他小样式,我经常这样做,您可以通过这种方式一次性设置它们。

import seaborn
seaborn.set_style('darkgrid', {'legend.frameon':True})
根据文档,您可以使用seaborn.axes_style()来获取seaborn当前的rc设置。
{'axes.axisbelow': True,
 'axes.edgecolor': '.8',
 'axes.facecolor': 'white',
 'axes.grid': True,
 'axes.labelcolor': '.15',
 'axes.linewidth': 1.0,
 'figure.facecolor': 'white',
 'font.family': [u'sans-serif'],
 'font.sans-serif': [u'Arial',
  u'DejaVu Sans',
  u'Liberation Sans',
  u'Bitstream Vera Sans',
  u'sans-serif'],
 'grid.color': '.8',
 'grid.linestyle': u'-',
 'image.cmap': u'rocket',
 'legend.frameon': False,
 'legend.numpoints': 1,
 'legend.scatterpoints': 1,
 'lines.solid_capstyle': u'round',
 'text.color': '.15',
 'xtick.color': '.15',
 'xtick.direction': u'out',
 'xtick.major.size': 0.0,
 'xtick.minor.size': 0.0,
 'ytick.color': '.15',
 'ytick.direction': u'out',
 'ytick.major.size': 0.0,
 'ytick.minor.size': 0.0}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接