简体   繁体   中英

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

在此输入图像描述

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: 在此输入图像描述 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 ay range that is too wide like in the first example. Only the last axis seems to have this problem. Any clue?

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:

在此输入图像描述

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:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM