seaborn:带有背景颜色的图例

seaborn: legend with background color

以下问题解释了如何更改图例的背景颜色: 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()

seaborn 默认关闭图例框架,如果你想自定义框架的外观,我想你需要在调用 plt.legend 时添加 frameon=True

set_style() 方法可以采用样式参数(例如 'white''whitegrid''darkgrid' 等)和参数字典来覆盖默认美学,包括是否打开图例框

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

import seaborn
seaborn.set_style('darkgrid', {'legend.frameon':True})

根据 the docs,您可以通过 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}