[英]How can I set the x-axis tick locations for a bar plot created from a pandas DataFrame?
[英]How to plot a vertical line on a bar plot with a datetime label with only discreet x-axis tick locations?
我正在嘗試使用axvline
plot 垂直線,但最終出現以下錯誤。
更新:問題與發布的參考文獻有所不同,因為只使用了謹慎的 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" )
您可以使用 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.