简体   繁体   English

错误的y轴范围使用matplotlib子图和seaborn

[英]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. 我是第一次玩seaborn,尝试使用matplotlib子图在不同的图上绘制不同的pandas数据列。 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). 下面的简单代码产生了预期的数字,但最后一个图没有正确的y范围(它似乎与数据帧中的整个值范围相关联)。 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: 如果您想手动更改特定ax的限制,可以在绘图命令的末尾添加此行:

ax4.set_ylim(top=5) 

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

Which will give something like this: 哪个会给出这样的东西:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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