组合Pandas图时与ylim的问题

2024-04-20 05:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题与我的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.0, 4917.985892131057)

图表如下所示:

enter image description here

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

enter image description here

在这种情况下get_ylim()就是(-613.14902407399052, 16197.881540891121)。你知道吗

我已经通过手动输入ylim获得了第二个图形。你知道吗

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

非常感谢!你知道吗


Tags: dataframedfgetplot图表pltcolabs
3条回答

将所有绘图添加到图形后,您可能希望自动缩放该图形。你知道吗

ax.autoscale()

为了使数据的底部在y方向上固定为零,可以使用ax.set_ylim(0,None)和x方向ax.margins(x=0)。你知道吗

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

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()
ax=df[["A", "B", "C"]].plot.area(ax=ax)
ax=df["D"].plot.line(ax=ax, color='red')

ax.get_legend().remove()

ax.autoscale()
ax.set_ylim(0,None)
ax.margins(x=0)

plt.show()

enter image description here

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

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

enter image description here

相关问题 更多 >