ℕʘʘ*_*ḆḽḘ 3 python matplotlib pandas
我希望我创建的垂直线能够以与ax.vlines图表相同的方式触及图表的上限和下限axvline。
考虑这个简单的例子:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'time' : [pd.to_datetime('2016-01-02'), pd.to_datetime('2016-01-03'), pd.to_datetime('2016-01-04')],
'value1' : [1, 2, 3],
'value2' : [10, 20, 30]})
df.set_index('time', inplace = True)
df
Out[95]:
value1 value2
time
2016-01-02 1 10
2016-01-03 2 20
2016-01-04 3 30
Run Code Online (Sandbox Code Playgroud)
现在的图表是:
fig, ax = plt.subplots(figsize=(30, 15))
ax.plot(df.index, df["value1"], color = 'black')
ax2 = ax.twinx()
ax2.plot(df.index, df["value2"], color = 'red')
#axvline stretches nicely
ax.axvline( pd.to_datetime('2016-01-04'), color = 'red', alpha = 1, linestyle = '--')
#vlines stops before touching the upper and lower boundaries
ymin, ymax = ax2.get_ylim()
ax.vlines([pd.to_datetime('2016-01-02'), pd.to_datetime('2016-01-03')], ymin = ymin, ymax = ymax, color = 'blue', linestyle = '-')
Run Code Online (Sandbox Code Playgroud)
给出:
您可以看到那些蓝线保留在空中,而漂亮的红色垂直线完全延伸。我怎样才能做到这一点?
谢谢!
您可能想要做的是使蓝线独立于 y 方向的数据。这可以使用xaxis_transform并将 ymin 和 ymax 分别设置为 0 和 1 来完成。
ax.vlines([pd.to_datetime('2016-01-02'), pd.to_datetime('2016-01-03')],
ymin = 0, ymax = 1, color = 'blue', linestyle = '-',
transform=ax.get_xaxis_transform())
Run Code Online (Sandbox Code Playgroud)
因此,我们模仿与使用完全相同的行为axvline,即对 x 值使用数据变换,对 y 值使用轴变换。轴内坐标的范围为 0 到 1,因此使用这些值将始终让线条从 y 轴的一端开始并到达另一端,无论其数据范围如何。
| 归档时间: |
|
| 查看次数: |
3974 次 |
| 最近记录: |