Volty
Volty

Reputation: 41

wrong y axis range using matplotlib subplots and seaborn

I'm playing with seaborn for the first time, trying to plot different columns of a pandas dataframe on different plots using matplotlib subplots. The simple code below produces the expected figure but the last plot does not have a proper y range (it seems linked to the full range of values in the dataframe). Does anyone have an idea why this happens and how to prevent it? Thanks.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pds
import seaborn as sns

X = np.arange(0,10)
df = pds.DataFrame({'X': X, 'Y1': 4*X, 'Y2': X/2., 'Y3': X+3, 'Y4': X-7})

fig, axes = plt.subplots(ncols=2, nrows=2)
ax1, ax2, ax3, ax4 = axes.ravel()
sns.set(style="ticks")
sns.despine(fig=fig)

sns.regplot(x='X', y='Y1', data=df, fit_reg=False, ax=ax1)
sns.regplot(x='X', y='Y2', data=df, fit_reg=False, ax=ax2)
sns.regplot(x='X', y='Y3', data=df, fit_reg=False, ax=ax3)
sns.regplot(x='X', y='Y4', data=df, fit_reg=False, ax=ax4)

plt.show()

enter image description here

Update: I modified the above code with:

fig, axes = plt.subplots(ncols=2, nrows=3)
ax1, ax2, ax3, ax4, ax5, ax6 = axes.ravel()

If I plot data on any axis but the last one I obtain what I'm looking for: enter image description here Of course I don't want the empty frames. All plots present the data with a similar visual aspect. When data is plotted on the last axis, it gets a y range that is too wide like in the first example. Only the last axis seems to have this problem. Any clue?

Upvotes: 4

Views: 6446

Answers (1)

Primer
Primer

Reputation: 10302

If you want the scales to be the same on all axes you could create subplots with this command:

fig, axes = plt.subplots(ncols=2, nrows=2, sharey=True, sharex=True)

Which will make all plots to share relevant axis:

enter image description here

If you want manually to change the limits of that particular ax, you could add this line at the end of plotting commands:

ax4.set_ylim(top=5) 

# or for both limits like this: 
# ax4.set_ylim([-2, 5])

Which will give something like this:

enter image description here

Upvotes: 2

Related Questions