海伯恩:有背景的传奇

2024-04-20 07:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

with matplotlibwith seaborn


Tags: importgetplotmatplotlibasshownpplt
2条回答

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}

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

相关问题 更多 >