在matplotlib.pyplot中进行绘图时如何显示日期? [英] How do I display dates when plotting in matplotlib.pyplot?

查看:768
本文介绍了在matplotlib.pyplot中进行绘图时如何显示日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个python代码,用于显示一段时间内的一些数字:

I have this python code for displaying some numbers over time:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, i).strftime("%Y-%m-%d") for i in range(1,5)], 
            dtype='datetime64')
y = np.array([1,-1,7,-3])
plt.plot(x,y)
plt.axhline(linewidth=4, color='r')
plt.show()

结果图的x轴上的数字为0.0到3.0:

The resulting graph has the numbers 0.0 to 3.0 on the x-axis:

显示日期而不是显示这些数字的最简单方法是什么?最好采用%b%d的格式.

What is the simplest way to display dates instead of these numbers? Preferably in the format %b %d.

推荐答案

根据要求,matplotlib不支持NumPy datetime64对象(至少目前还不支持).因此,将x转换为Python datetime.datetime对象:

According to efiring, matplotlib does not support NumPy datetime64 objects (at least not yet). Therefore, convert x to Python datetime.datetime objects:

x = x.astype(DT.datetime)

接下来,您可以像这样指定x轴刻度线格式器:

Next, you can specify the x-axis tick mark formatter like this:

xfmt = mdates.DateFormatter('%b %d')
ax.xaxis.set_major_formatter(xfmt)


import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as DT
import numpy as np

x = np.array([DT.datetime(2013, 9, i).strftime("%Y-%m-%d") for i in range(1,5)], 
            dtype='datetime64')
x = x.astype(DT.datetime)
y = np.array([1,-1,7,-3])
fig, ax = plt.subplots()
ax.plot(x, y)
ax.axhline(linewidth=4, color='r')
xfmt = mdates.DateFormatter('%b %d')
ax.xaxis.set_major_formatter(xfmt)
plt.show()

这篇关于在matplotlib.pyplot中进行绘图时如何显示日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆