如何为matplotlib设置x轴上的日期格式

2024-10-01 13:35:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图得到一个dataframe列来在图表上显示日期,例如“1月15日、2月15日等等”。但是它显示为“feb115,Mar 115等等”,我尝试使用matplotlib.ticker. 但是图表上没有轴。这里是代码的简化版本,不起作用。在

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()

Tags: 代码import版本dataframematplotlibas图表plt
1条回答
网友
1楼 · 发布于 2024-10-01 13:35:24

以下是一些工作代码:

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()

说明:

结果显示,msexcel中的连续日期从1899年12月30日开始。i、 数字0是1899年12月30日,1对应于1899年12月31日(自己在Excel中试试看)。虽然the Excel help说“1900年1月1日是序列号1”,但这是不正确的,因为an early bug似乎是固定的。在

要将Excel序列日期转换为Python日期时间对象,请签出datetime.timedelta。在

要在matplotlib中绘制日期时间,请签出其demoAPI。在

相关问题 更多 >