简体   繁体   English

如何在x轴上为matplotlib格式化日期

[英]How to format Dates on x axis for matplotlib

I am trying to get a dataframe column to display the date as example "Jan 15, Feb 15 etc" on a chart. 我试图获取一个数据框列以在图表上显示日期,例如“ Jan 15,Feb 15 etc”。 But it was displaying as "Feb 115, Mar 115 etc" I have tried to adapt some code using matplotlib.ticker. 但是它显示为“ Feb 115,Mar 115 etc”,我试图使用matplotlib.ticker修改一些代码。 but then the chart comes out with no axis. 但随后图表就没有了轴。 Here is a simplified version of the code, not working. 这是代码的简化版本,无法正常工作。

import matplotlib.pyplot as plt
import matplotlib.ticker as tkr


# create figure instance
fig1 = plt.figure(1)

ax = fig1.add_subplot(2,1,1)

x = 41640, 41671, 41699, 41730, 41760, 41791

y = 1, 4, 7, 9, 15, 18

ax.get_xaxis().set_major_formatter(
    tkr.FuncFormatter(lambda x, p: format((x), '%b %y')))


ax.plot_date(x, y)
fig1.show()

Here is some working code: 这是一些工作代码:

import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
import matplotlib.dates as mdates
import datetime

# create figure instance
fig1 = plt.figure(1)
ax = fig1.add_subplot(2,1,1)

start_date = datetime.date(1899, 12, 30)
x = 41640, 41671, 41699, 41730, 41760, 41791
dates = [start_date + datetime.timedelta(xval) for xval in x]
y = 1, 4, 7, 9, 15, 18

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator(bymonthday=(1,15)))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
plt.plot(dates, y, 'o')
plt.show()

Explanation: 说明:

It turns out serial dates in MS Excel start from Dec 30, 1899. ie number 0 is Dec 30, 1899, and 1 corresponds to Dec 31, 1899 (try it out in Excel yourself ^_^). 原来,MS Excel中的序列日期是从1899年12月30日开始的。即数字0是1899年12月30日,而1对应于1899年12月31日(请自己在Excel中试用^ _ ^)。 Although the Excel help says that "January 1, 1900 is serial number 1", it is incorrect, since there was an early bug that seems to be fixed. 尽管Excel帮助中说“ 1900年1月1日是序列号1”,但这是不正确的,因为似乎已经修复了一个早期的错误

To convert the Excel serial dates to a Python datetime object, checkout datetime.timedelta . 要将Excel序列日期转换为Python datetime对象,请签出datetime.timedelta

To plot datetime in matplotlib, checkout its demo and API . 要在matplotlib中绘制日期时间,请查看其演示API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM