python - 组合 pandas 绘图时 ylim 的问题

标签 python pandas matplotlib

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

图表如下所示:

enter image description here

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

enter image description here

在这种情况下,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()

enter image description here

关于python - 组合 pandas 绘图时 ylim 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47529735/

相关文章:

Python:为什么 __str__ 不调用递归?

python - 为什么这个 Keras 模型需要超过 6GB 的内存?

python dataframe pandas使用int删除列

python - 如何在python中将网页转换为pdf,就像打印中的另存为pdf选项一样

python-3.x - Apache NiFi : Import Error: No module named Pandas 中的 Python 错误

python - 灰度框架上的 numpy.where(),索引错误?

python - Matplotlib:如何去除热图中的白线

python - 使用 pandas 部分取消透视表

python - 如何迭代一行并相互比较?

python - 具有约 2000 万个样本点和千兆字节数据的交互式大图