python - How to plot 2 seaborn lmplots side-by-side? -
plotting 2 distplots or scatterplots in subplot works great:
import matplotlib.pyplot plt import numpy np import seaborn sns import pandas pd %matplotlib inline # create df x = np.linspace(0, 2 * np.pi, 400) df = pd.dataframe({'x': x, 'y': np.sin(x ** 2)}) # 2 subplots f, (ax1, ax2) = plt.subplots(1, 2, sharey=true) ax1.plot(df.x, df.y) ax1.set_title('sharing y axis') ax2.scatter(df.x, df.y) plt.show()
but when same lmplot
instead of either of other types of charts error:
attributeerror: 'axessubplot' object has no attribute 'lmplot'
is there way plot these chart types side side?
you error because matplotlib , objects unaware of seaborn functions.
pass axes objects (i.e., ax1
, ax2
) seaborn.regplot
or can skip defining , use col
kwarg of seaborn.lmplot
with same imports, pre-defining axes , using regplot
looks this:
# create df x = np.linspace(0, 2 * np.pi, 400) df = pd.dataframe({'x': x, 'y': np.sin(x ** 2)}) df.index.names = ['obs'] df.columns.names = ['vars'] idx = np.array(df.index.tolist(), dtype='float') # make array of x-values # call regplot on each axes fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=true) sns.regplot(x=idx, y=df['x'], ax=ax1) sns.regplot(x=idx, y=df['y'], ax=ax2)
using lmplot requires dataframe tidy. continuing code above:
tidy = ( df.stack() # pull columns row variables .to_frame() # convert resulting series dataframe .reset_index() # pull resulting multiindex columns .rename(columns={0: 'val'}) # rename unnamed column ) sns.lmplot(x='obs', y='val', col='vars', hue='vars', data=tidy)
Comments
Post a Comment