[matplotlib]:在 x 轴上写日期 [英] [matplotlib]: write dates on x axis

查看:65
本文介绍了[matplotlib]:在 x 轴上写日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个示例代码,我想在其中在x轴上绘制整个日期

Here an example code in which I would like to draw the entire date on the x axis

import datetime
import matplotlib.pyplot as plt
import random
import numpy as np
from matplotlib.dates import DateFormatter

years = np.arange( 2005, 2016, 1)
years[1] = 2005
years[2] = 2005
months = [ 3, 2, 1, 5, 7, 12, 2, 3, 5, 2, 6]
dates = []
for Y in years:
    dates = dates + [ datetime.datetime(Y, 6 , 4) ]


y = np.random.randn(len(dates))

fig, ax = plt.subplots()

ax.plot_date(dates, y, 'r+', ms = 2, mew = 12)

ax.fmt_xdata = DateFormatter('%y-%m-%d')
fig.autofmt_xdate()

plt.show()

不幸的是,结果是这样

我需要的是像这张图片一样在 x 轴上写下所有的日期

And what I need is to write all the date on the x axis like in this picture

您建议我更改我的代码吗?

What you suggest me to change on my code?

推荐答案

ax.fmt_xdata 是日期格式,通常仅用于交互式绘图中的悬停功能.

ax.fmt_xdata is the formatter for the dates usually only used for the hover functionality in interactive plots.

您要在此处将xaxis的主要格式化程序设置为 DateFormatter :

What you want here is to set the major formatter of the xaxis to a DateFormatter:

ax.xaxis.set_major_formatter(DateFormatter('%b-%d-%Y'))

这篇关于[matplotlib]:在 x 轴上写日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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