影响情节轴的横线

2024-09-29 21:39:18 发布

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

我正在试验axhline,我发现了不可预测的行为。当我添加一个axhline时,它有时会把我的x-axis完全弄乱,有时却不会。在

设置

import matplotlib.pyplot as plt
import pandas as pd

idx = pd.date_range('2016-01-01', '2016-03-31')
ts = pd.Series([0. for d in idx], index=idx)
t1 = ts['2016-01'] + 1
t2 = ts['2016-02'] + 2
t3 = ts['2016-03'] + 3

第一试验区

enter image description here

正是我想要的。在

问题

现在让我们添加一个axhline

^{pr2}$

enter image description here

完全不是我所期待的!在

然而

如果我在末尾加上axhline。在

ax = ts.plot()
t1.plot(ax=ax)
t2.plot(ax=ax)
t3.plot(ax=ax)
ax.axhline(y=1.5)
plt.ylim([-1, 4]);

enter image description here

没问题。在

为什么!?在

为什么我的绘图顺序决定了x轴的比例?在

版本

import matplotlib
print pd.__version__
print matplotlib.__version__

0.18.0
1.5.1

Tags: importplotmatplotlibversionaspltaxpd
1条回答
网友
1楼 · 发布于 2024-09-29 21:39:18

“问题”情节没有错。您只需要重新缩放x轴,以便时间刻度从2016年开始。如果你仔细观察“问题”图,你会看到在图的右端有三个点。在

快速修复方法:

ax = ts.plot()
ax.axhline(y=1.5)
t1.plot(ax=ax)
t2.plot(ax=ax)
t3.plot(ax=ax)
plt.autoscale()
plt.ylim([-1, 4])
plt.show()

好像在pyplot中,如果您首先创建axhline,那么您必须在plt.show()之前重新缩放。在

相关问题 更多 >

    热门问题