Matplotlib has an extended styling and configuration interface which allows to control most of the plot aesthetics. Seaborn adds more preset styles and color palettes and some more control, too. This allows the preparation of print- and publication-ready figures, user customization, and easy switching between plotting styles.
This session roughly follows and extends on Data visualization in Python by Randy Olson.
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
print("Matplotlib version:", mpl.__version__)
Matplotlib version: 2.0.0
x1_values = [2012, 2013, 2014, 2015]
y1_values = [4.3, 2.5, 3.5, 4.5]
x2_values = [2012, 2013, 2014, 2015]
y2_values = [2.4, 4.4, 1.8, 2.8]
x3_values = [2012, 2013, 2014, 2015]
y3_values = [2, 2, 3, 5]
def example_plot():
plt.plot(x1_values, y1_values, label='Python')
plt.plot(x2_values, y2_values, label='JavaScript')
plt.plot(x3_values, y3_values, label='R')
plt.xlim(2012, 2015)
plt.ylim(0, 6)
plt.xticks([2012, 2013, 2014, 2015], ['2012', '2013', '2014', '2015'])
plt.yticks([1, 2, 3, 4, 5])
plt.xlabel('Year')
plt.ylabel('Web searches')
plt.legend(loc='upper center', ncol=3)
plt.grid(True)
example_plot()
rcParams
¶You can change matplotlib's settings using the dictionary plt.rcParams
:
plt.rcParams['figure.figsize'] = (8, 5) # for presentations
plt.rcParams['axes.prop_cycle'] = plt.cycler('color', ['#1f33e4', '#337f0e', '#40306c'])
plt.rcParams['lines.linewidth'] = 3
example_plot()
print(plt.style.available)
['bmh', 'classic', 'dark_background', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn']
with plt.style.context('fivethirtyeight'):
example_plot()
Repeat the above plot using one of the styles available via matplotlib.style.context
.
You can define your own style by creating an .mplstyle
file in the folder stylelib
in your matplotlib config folder.
cfgdir = mpl.get_configdir()
%ls $cfgdir
fontList.cache fontList.py3k.cache tex.cache/
import os
style_path = os.path.join(cfgdir, 'stylelib')
if not os.path.exists(style_path):
os.makedirs(style_path)
style_path = os.path.join(style_path, 'rhiever.mplstyle')
print(style_path)
/Users/yoavram/.matplotlib/stylelib/rhiever.mplstyle
%%writefile $style_path
figure.figsize: 12, 7
figure.edgecolor: white
figure.facecolor: white
lines.linewidth: 2.5
lines.markeredgewidth: 0
lines.markersize: 10
lines.dash_capstyle: butt
legend.fancybox: True
font.size: 14
axes.prop_cycle: cycler('color', ['1f77b4', 'ff7f0e', '2ca02c', 'd62728', '9467bd', '8c564b', 'e377c2', '7f7f7f', 'bcbd22', '17becf'])
axes.linewidth: 0
axes.titlesize: 22
axes.labelsize: 16
xtick.labelsize: 14
ytick.labelsize: 14
xtick.major.size: 0
xtick.minor.size: 0
ytick.major.size: 0
ytick.minor.size: 0
axes.grid: True
grid.alpha: 0.3
grid.linewidth: 0.5
grid.linestyle: --
grid.color: black
savefig.transparent: False
savefig.bbox: tight
savefig.format: png
Writing /Users/yoavram/.matplotlib/stylelib/rhiever.mplstyle
plt.style.reload_library()
print(plt.style.available)
['bmh', 'classic', 'dark_background', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'rhiever']
with plt.style.context('rhiever'):
example_plot()
This style was copied from Randy Olson.
with plt.style.context(stylename):
for setting the style of specific plots.plt.style.use(stylename)
to set the style of all plots in the current session.Seaborn adds a bunch of styles and also gives a different interface for setting plot aesthetics, color palettes, and contexts.
import seaborn as sns
print('Seaborn version:', sns.__version__)
Seaborn version: 0.7.1
sns.set(
style='dark',
context='talk',
palette='Set1'
)
example_plot()
You can change the style used by matplotlib by calling seaborn.set_style
:
sns.set_style('white')
example_plot()
Some styles can benefit from removing the top and right axes spines, which are not needed. It’s impossible to do this through the matplotlib parameters, but you can call the Seaborn function despine()
to remove them:
example_plot()
sns.despine()
Some plots benefit from offsetting the spines away from the data, which can also be done when calling despine()
. When the ticks don’t cover the whole range of the axis, the trim
parameter will limit the range of the surviving spines.
example_plot()
sns.despine(offset=10, trim=True)
Similar to mpl.style.context
, you can set a Seaborn style for a specific code block using a context manager created by axes_style
:
with sns.axes_style("darkgrid"):
example_plot()
example_plot()
Seaborn has many color palettes to choose from, including the famous Colorbrewer palettes and Seaborn's own palettes.
You can plot a color palette to see the colors using sns.palplot
:
sns.set_palette('Greens')
sns.palplot(sns.color_palette())
example_plot()
sns.set_palette('dark')
sns.palplot(sns.color_palette())
example_plot()
Seaborn's contexts automatically control the scaling and proportions according to the target of the plot - notebook
, talk
, paper
. poster
. In addition, you can scale the font size and set any rcParam
you want:
sns.set_palette(sns.color_palette('Set2'))
sns.set_context('paper', font_scale=2, rc={'lines.linewidth': 8})
example_plot()
Use Seaborn styles and contexts and plot the example plot.
This notebook was written by Yoav Ram and is part of the Python for Engineers course.
The notebook was written using Python 3.6.1. Dependencies listed in environment.yml, full versions in environment_full.yml.
This work is licensed under a CC BY-NC-SA 4.0 International License.