python - 垂直线不出现在 matplotlib 图中

标签 python numpy matplotlib plot

我有一个代码可以让我绘制两个时间序列的数据。我还有一些事件,我将它们绘制为时间序列中的一系列垂直线。我有三年的时间序列:2015 年、2016 年和 2017 年。我的代码在 2015 年和 2016 年运行良好,我生成了这样的图表(这是 2016 年的):Timeseries data (red and blue) and event data (dotted vertical lines) plotted.

但是,当我绘制 2017 年的数据时,我无法重现事件数据的垂直线,如下所示(很难看到,但在此图中没有像第一个那样的垂直虚线):

Timeseries data (red and blue) but no event data plotted.

关于为什么我的代码不适用于 2017 年的任何想法?数据存储在 .csv 文件中,事件数据是根据我已转换为一系列日期时间对象的 .csv 文件中的一列数据绘制的。我检查过,2015、2016 和 2017 .csv 文件的格式保持不变。

仅供引用,这是我用来绘制的代码:

#Change format of "dates" column from string to datetime object    
FMT = '%d/%m/%Y'
dtlist = []
for i in range(0, len(dates)):
    dtlist.append(datetime.datetime.strptime(dates[i], FMT))  


##EVENT:
#Remove all values where there is no event
df2 = df_17[pd.notnull(df_17['event'])]

#Convert event values to datetime objects
df2['event'] = pd.to_datetime(df2['event'], format="%d/%m/%Y")
event_list = df2['event'].tolist()

#Plot timeseries on graph
fig, ax1 = plt.subplots(figsize=(18, 6))
plt.plot(dtlist, series_1, color='b', label='Series 1')
ymin, ymax = ax1.get_ylim()
for value in event_list:
    plt.axvline(x=value, ymin=ymin, ymax=ymax-1, color='k', linewidth=1.0, linestyle='--')    
ax1.set_xlabel('Time')
ax1.set_ylabel('Series 1')

ax2=ax1.twinx()
ax2.plot(dtlist, series_2, color='r', label='Series_2')
ax2.set_ylabel('Series 2')

plt.legend
plt.show()

非常感谢任何帮助!

最佳答案

在评论中,您说您从 Pandas graphing a timeseries, with vertical lines at selected dates 得到了关于 yminymax 的值的想法| , 但那里的例子使用 vlines , 不是 axvline . vlines 使用数据比例。 axvline 期望 yminymax 的值介于 0 和 1 之间。也就是说,y 值以 y 轴的小数部分(介于 0 和 1 之间)指定。例如,如果您指定 ymin=0ymax=0.5,您将得到一条从轴底部到轴中间的垂直线,无论该图的当前数据比例。如果您放大或缩小,或者向上或向下平移,半高垂直线会保留。

yminymax 的默认值分别为 0 和 1,因此要获得一条从底部到顶部的线,您可以简单地省略论点。

试试这个:

    plt.axvline(x=value, color='k', linewidth=1.0, linestyle='--') 

关于python - 垂直线不出现在 matplotlib 图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45418953/

相关文章:

python - 无法并排绘制多个水平条

python - 组合补丁以获得 matplotlib 中的单一透明度

python - 如何从 matplotlib 中删除工具栏按钮

python - 这是哈希函数吗? Python

python - 在 Tensorflow 中使用大型数据集

python - “符号”对象没有属性 'sin'

python - 2D 数组的 Numpy 按元素均值计算

python - Pylab/Matplotlib 将多个饼图合并为一个 PDF

Python 3d 散点图颜色图问题

python - 作为输入传递给 Keras 中的输入时 numpy 数组的形状