使用pyplot为数据帧错误的日期(偏移一天)

时间:2018-03-20 18:29:34

标签: python python-3.x pandas matplotlib

我正在使用pyplot作为pandas数据帧,以更好地控制轴格式。我遇到的一个问题是日期被抵消了一天。

import pandas as pd
from pandas import Timestamp
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


'''
Matplotlib version: '2.1.1'
'''

data = {'test': {Timestamp('2018-02-28 00:00:00'): 84498100.41000001,
  Timestamp('2018-03-31 00:00:00'): 84498100.41000001,
  Timestamp('2018-04-30 00:00:00'): 84498100.41000001,
  Timestamp('2018-05-31 00:00:00'): 84498100.41000001,
  Timestamp('2018-06-30 00:00:00'): 84498100.41000001,
  Timestamp('2018-07-31 00:00:00'): 84498100.41000001,
  Timestamp('2018-08-31 00:00:00'): 84498100.41000001,
  Timestamp('2018-09-30 00:00:00'): 84498100.41000001,
  Timestamp('2018-10-31 00:00:00'): 84498100.41000001,
  Timestamp('2018-11-30 00:00:00'): 84498100.41000001,
  Timestamp('2018-12-31 00:00:00'): 84498100.41000001,
  Timestamp('2019-01-31 00:00:00'): 84498100.41000001,
  Timestamp('2019-02-28 00:00:00'): 84498100.41000001}}


df = pd.DataFrame.from_dict(data)

fig, ax = plt.subplots()
fig.set_size_inches(10,10)

ax.set_xticklabels(df.index, rotation=90)
ax.bar(x=df.index, height=df['test'], width=15)

#x axis

months = mdates.MonthLocator()
ax.xaxis.set_major_locator(months)
monthFmt = mdates.DateFormatter('%d/%b')
ax.xaxis.set_major_formatter(monthFmt)

结果图表:

Pic of Chart

数据框:

dataframe picture

编辑:要清楚,我正在寻找显示日期: 28 / Feb,31 / Mar等

1 个答案:

答案 0 :(得分:1)

如果没有进一步的论证,mdates.MonthLocator()将在每个月的第一天打勾。在这里,您似乎根本不需要任何自动位置,而是精确地来自数据框索引的那些位置。这可以通过将xticks设置为这些日期来实现,

ax.set_xticks(df.index)

然后,你仍然可以使用格式化程序来获得漂亮的ticklabel格式。

import pandas as pd
from pandas import Timestamp
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

data = {'test': {Timestamp('2018-02-28 00:00:00'): 84498100.41000001,
  Timestamp('2018-03-31 00:00:00'): 84498100.41000001,
  Timestamp('2018-04-30 00:00:00'): 84498100.41000001,
  Timestamp('2018-05-31 00:00:00'): 84498100.41000001,
  Timestamp('2018-06-30 00:00:00'): 84498100.41000001,
  Timestamp('2018-07-31 00:00:00'): 84498100.41000001,
  Timestamp('2018-08-31 00:00:00'): 84498100.41000001,
  Timestamp('2018-09-30 00:00:00'): 84498100.41000001,
  Timestamp('2018-10-31 00:00:00'): 84498100.41000001,
  Timestamp('2018-11-30 00:00:00'): 84498100.41000001,
  Timestamp('2018-12-31 00:00:00'): 84498100.41000001,
  Timestamp('2019-01-31 00:00:00'): 84498100.41000001,
  Timestamp('2019-02-28 00:00:00'): 84498100.41000001}}


df = pd.DataFrame.from_dict(data)

fig, ax = plt.subplots()
fig.set_size_inches(10,5)

ax.bar(x=df.index, height=df['test'], width=15)

#x axis
ax.set_xticks(df.index)
monthFmt = mdates.DateFormatter('%d/%b')
ax.xaxis.set_major_formatter(monthFmt)
fig.autofmt_xdate( rotation=90, ha="center")

enter image description here