I'm trying to change the styles of two plots that are in the same figure:
import numpy as np
from numpy.random import randn
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(15,6))
data = randn(7500);
sns.set_style("whitegrid");
ax1.hist(data, bins=8);
sns.set_style("darkgrid");
ax2.hist(data, bins=8);
This does not work, both plots end up having the "darkgrid"
background. I have also trying tinkering with axes_style()
with no success.
The way matplotlib Axes work is that the style parameters become a property of the Axes object at the time it is created, not at the time something is drawn onto it. So while it's not possible to make a figure that has different subplot styles using plt.subplots
, you can do it with one of the ways where you independently create the Axes:
fig = plt.figure()
with sns.axes_style("whitegrid"):
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
Note also that I'm using a context manager to style the first Axes, so the second Axes will have the default style. It's possible to use sns.set_style
before each add_subplot
command like you do in the question, but using the context manager to create the non-default plot feels a little bit more Pythonic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With