Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 组合熊猫图时与ylim有关的问题_Python_Pandas_Matplotlib - Fatal编程技术网

Python 组合熊猫图时与ylim有关的问题

Python 组合熊猫图时与ylim有关的问题,python,pandas,matplotlib,Python,Pandas,Matplotlib,在熊猫中结合面积图和线图时,我的y轴比例有问题 下面是一个例子来说明这一点: df= pd.DataFrame(abs(np.random.randn(50, 4)), columns=list('ABCD')) for col in ["A", "B", "C"]: df[col]=df[col]*1000 df["D"]=df["D"]*5000 fig, ax = plt.subplots(figsize=(28, 10)) ax=df[["A", "B", "C"]].plot

在熊猫中结合面积图和线图时,我的y轴比例有问题

下面是一个例子来说明这一点:

df= pd.DataFrame(abs(np.random.randn(50, 4)), columns=list('ABCD'))
for col in ["A", "B", "C"]:
    df[col]=df[col]*1000
df["D"]=df["D"]*5000

fig, ax = plt.subplots(figsize=(28, 10))
ax=df[["A", "B", "C"]].plot.area(ax=ax)
ax=df["D"].plot.line(ax=ax, color='red')
print(ax.get_ylim())
ax.margins(0, 0)
ax.legend_.remove()
plt.show()
ax.get_ylim()
的结果是:
(0.04917.985892131057)

图表如下所示:

如您所见,图表在顶部被裁剪,我缺少关于图D的信息。预期结果为:

在这种情况下,
get_ylim()
(-613.1490240739905216197.881540891121)

我通过手动输入ylim获得了第二张图

你能告诉我我做错了什么吗?在我的示例中,为什么我不能从我的“D”图中获得
y_lim


非常感谢

添加所有绘图后,您可能希望自动缩放图形

ax.autoscale()
为了使数据的底部在y方向上紧靠零,可以使用
ax.set_ylim(0,None)
和x方向
ax.margins(x=0)


我认为这是因为限值最初是由绘制的第一组数据设定的。试着换一下:

ax=df["D"].plot.line(ax=ax, color='red')
ax=df[["A", "B", "C"]].plot.area(ax=ax)
但这同样取决于数据,只有当
“D”
始终大于其他值时,它才会起作用。您可以添加一行自动更新
ylim
,如下所示:

ax.set_ylim(top=df.values.max())

您可以使用
ax.set_ylim()
手动设置y轴限制。但我认为最好的方法是使用@ImportanceOfBeingErnest建议的
ax.autoscale()

fig, ax = plt.subplots(figsize=(28, 10))
ax.set_ylim(0, df.max().max()) # setting the upper y_limit to the maximum value in the dataframe
df[["A", "B", "C"]].plot.area(ax=ax)
df["D"].plot.line(ax=ax, color='red')

plt.show()

我也注意到了这一点。我不想改变顺序,因为当两个图之间有重叠时,线图是隐藏的。你的第二个选择可能是正确的选择。使用起来并不方便,但现在就可以了。谢谢
fig, ax = plt.subplots(figsize=(28, 10))
ax.set_ylim(0, df.max().max()) # setting the upper y_limit to the maximum value in the dataframe
df[["A", "B", "C"]].plot.area(ax=ax)
df["D"].plot.line(ax=ax, color='red')

plt.show()