seaborn: legend with background color

不想你离开。 提交于 2019-12-04 15:44:52

问题


The following question explains how to change the background color of a legend: matplotlib legend background color. However, if I use seaborn this does not work. Is there a way to do this?

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()


回答1:


seaborn turns the legend frame off by default, if you want to customize how the frame looks, I think you'll need to add frameon=True when you call plt.legend.




回答2:


The set_style() method can take a style argument (e.g. 'white', 'whitegrid', 'darkgrid', etc.) AND a dict of parameters to override defaults aesthetics, including whether to have the legend frame on or not.

If you have other little styling things you'd like to change, which I often do, you can just set them all at once this way.

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

As per the docs, you can get seaborn's current rc settings with seaborn.axes_style()

{'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}


来源:https://stackoverflow.com/questions/30729473/seaborn-legend-with-background-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!