【发布时间】:2021-03-01 06:26:29
【问题描述】:
我有这个数据框:
dates;A;B;C
2018-01-31;1;2;5
2018-02-28;1;4;3
2018-03-31;1;5;5
2018-04-30;1;6;3
2018-05-31;1;6;7
2018-06-30;1;7;3
2018-07-31;1;9;9
2018-08-31;1;2;3
2018-09-30;1;2;10
2018-10-31;1;4;3
2018-11-30;1;7;11
2018-12-31;1;2;3
我读过:
dfr = pd.read_csv('test.dat', sep=';', header = 0, index_col=0, parse_dates=True)
然后我尝试绘制它:
width = 5
dfr.index = pd.to_datetime(dfr.index)
x = date2num(dfr.index)
axs.bar(x-0.5*width,dfr.iloc[:,1], width=width)
axs.bar(x+0.5*width,dfr.iloc[:,2], width=width)
axs.xaxis_date()
months = dates.MonthLocator()
axs.xaxis.set_major_formatter(dates.DateFormatter(r'\textbf{%B}'))
months_f = dates.DateFormatter('%B')
axs.xaxis.set_major_locator(months)
plt.setp( axs.xaxis.get_majorticklabels(), rotation=90)
这里是导入的模块:
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime
import pandas as pd
import matplotlib.dates as dates
结果如下:
我不明白为什么 x 标签以“Feb”开头。 我想在 x 轴上使用类似 'Jan,Feb,Mar...' 作为 x 标签。
提前致谢
【问题讨论】:
-
不确定这是否仍然与您相关,但问题来自您手动设置条形位置的方式:如果您查看 x 轴数据,例如一月,您在与
2018-01-28和2018-02-02对应的日期绘制条形图,因为您基本上采用01-31并加/减2.5 天。快速修复:使用x = x -30。
标签: pandas datetime matplotlib bar-chart