seaborn: legend with background color

28.7k views Asked by At

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

with matplotlib with seaborn

2

There are 2 answers

1
mwaskom On BEST ANSWER

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.

0
ryanjdillon On

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}