【问题标题】:matplotlib plot from dataframe but shift dates in x labelsmatplotlib 从数据框中绘制,但在 x 标签中移动日期
【发布时间】: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-282018-02-02 对应的日期绘制条形图,因为您基本上采用01-31 并加/减2.5 天。快速修复:使用x = x -30

标签: pandas datetime matplotlib bar-chart


【解决方案1】:

您制作的条形图的高度与标记的月份不对应,即二月的值实际上是一月的值。因此,问题出在您标记轴的方式上,而不是绘制顺序不正确。

我对你使用的包不是很熟悉,所以我提出了一种不同的方式来制作你的情节:

dfr['dates'] = pd.to_datetime(dfr['dates'])
### group by months
month_vals = dfr.groupby(dfr['dates'].map(lambda x: x.month))
month_vals = sorted(month_vals, key=lambda m: m[0])

fig, axs = plt.subplots()

spacing = 0.15
### Create the list of months and the corresponding dataframes
months, df_months = zip(*month_vals)
### In your case, each month has exactly one entry, but in case there are more, sum over all of them 
axs.bar([m-spacing for m in months], [df_m.loc[:,'B'].sum() for df_m in df_months], width=0.3)
axs.bar([m+spacing for m in months], [df_m.loc[:,'C'].sum() for df_m in df_months], width=0.3)

axs.set_xticks(months)
### 1900 and 1 are dummy values; we are just initializing a datetime instance here
axs.set_xticklabels([datetime.date(1900, m, 1).strftime('%b') for m in months])

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2016-02-14
    • 2020-08-23
    • 2017-01-01
    相关资源
    最近更新 更多