Skip to main content
 首页 » 编程设计

python之axhline 影响绘图轴

2024年10月24日8think

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

设置

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 

第一个测试图

正是我想要的。

问题

现在让我们添加一个axhline

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

完全不是我所期待的!

然而

如果我在末尾添加 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]); 

没问题。

为什么!?

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

版本

import matplotlib 
print pd.__version__ 
print matplotlib.__version__ 
 
0.18.0 
1.5.1 

请您参考如下方法:

“问题”情节没有错。您只需重新缩放 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() 

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