【问题标题】:How to plot a vertical line on a bar plot with a datetime label with only discreet x-axis tick locations?如何在条形图上绘制一条垂直线,其日期时间标签只有谨慎的 x 轴刻度位置?
【发布时间】:2020-12-01 18:23:57
【问题描述】:

我正在尝试使用axvline 绘制一条垂直线,但最终出现以下错误。

更新:问题与发布的参考文献有所不同,因为只使用了谨慎的 x 轴刻度位置(如 Trenton McKinney 所述)。

错误

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

代码

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" ) 

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

您可以使用 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,);

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 1970-01-01
    • 2016-02-18
    • 2013-11-07
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多