简体   繁体   English

如何 plot 条上的垂直线 plot 与日期时间 label 只有谨慎的 x 轴刻度位置?

[英]How to plot a vertical line on a bar plot with a datetime label with only discreet x-axis tick locations?

I am trying to plot a vertical line using axvline but ending up with the following error.我正在尝试使用axvline plot 垂直线,但最终出现以下错误。

Update: the question deviates from posted references because only discreet x-axis tick locations are used (as stated by Trenton McKinney).更新:问题与发布的参考文献有所不同,因为只使用了谨慎的 x 轴刻度位置(如 Trenton McKinney 所述)。

Error错误

TypeError: '<' not supported between instances of 'Timestamp' and 'numpy.float64'

Code代码

import pandas as pd

df = pd.DataFrame({'A': {0: '2020-01-01 06:00:00', 
                    1: '2020-01-01 18:00:00', 
                    2: '2020-01-02 06:00:00',
                    3: '2020-01-02 18:00:00',
                    4: '2020-01-03 06:00:00',
                    5: '2020-01-03 18:00:00',
                    6: '2020-01-04 06:00:00',
                    7: '2020-01-04 18:00:00'},
              'B': {0: 5, 1: 5, 2: 6, 3:6, 4:7, 5:7, 6:1, 7:1}})

df['A'] = pd.to_datetime(df['A'])
df= df.set_index('A')
ax = df.plot.bar()
ax.axvline(pd.to_datetime('2020-01-02 18:00:00'), color='grey', zorder=1, linestyle='--', marker="v" ) 
ax.axvline(pd.to_datetime('2020-01-03 00:00:00'), color='grey', zorder=1, linestyle='--', marker="v" ) 

You could build your own barchart with a true datetime x-axis using ax.vlines:您可以使用 ax.vlines 构建您自己的带有真正日期时间 x 轴的条形图:

import pandas as pd
from matplotlib.dates import DateFormatter

df = pd.DataFrame({'A': {0: '2020-01-01 06:00:00', 
                    1: '2020-01-01 18:00:00', 
                    2: '2020-01-02 06:00:00',
                    3: '2020-01-02 18:00:00',
                    4: '2020-01-03 06:00:00',
                    5: '2020-01-03 18:00:00',
                    6: '2020-01-04 06:00:00',
                    7: '2020-01-04 18:00:00'},
              'B': {0: 5, 1: 5, 2: 6, 3:6, 4:7, 5:7, 6:1, 7:1}})

df['A'] = pd.to_datetime(df['A'])
df= df.set_index('A')
fig, ax = plt.subplots()
ax.vlines(df.index, [0]*df.shape[0], df['B'], lw=25)
ax.axvline(pd.Timestamp('2020-01-02 18:00:00'), color='grey', zorder=1, linestyle='--', marker="v" ) 
ax.axvline(pd.Timestamp('2020-01-03 00:00:00'), color='grey', zorder=1, linestyle='--', marker="v" )
myFmt = DateFormatter("%m/%d/%Y %H:%M:%S")
ax.xaxis.set_major_formatter(myFmt)
ax.set_xticks(df.index)
for label in ax.xaxis.get_ticklabels():
    label.set_rotation(90)
ax.set_ylim(0,);

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM