在 Pandas 中将面积图与线图组合时,我的 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)
图表如下所示:
正如您所看到的,图表在顶部被裁剪,我缺少有关图 D 的信息。预期结果是:
在这种情况下,get_ylim()
是(-613.14902407399052, 16197.881540891121)
。
我通过手动输入 ylim 获得了第二张图。
你能让我知道我做错了什么吗?为什么我无法从示例中的“D”图中获取 y_lim
?
提前非常感谢!
最佳答案
您可能希望在添加所有绘图后自动缩放图表。
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()
关于python - 组合 pandas 绘图时 ylim 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47529735/