如何在matplotlib中设置日期的xticklabels [英] How to set the xticklabels for date in matplotlib

查看:33
本文介绍了如何在matplotlib中设置日期的xticklabels的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从两个列表中绘制值.x 轴值为日期.到目前为止已经尝试过这些东西

I am trying to plot values from two list. The x axis values are date. Tried these things so far

year = [20070102,20070806,20091208,20111109,20120816,20140117,20140813]
yvalues = [-0.5,-0.5,-0.75,-0.75,-0.5,-1.25,-1.25]

dates = [datetime.datetime.strptime(str(int(date)),'%Y%m%d') for date in year]

fig, axes = plt.subplots(1, 1, figsize=(16, 9), dpi=100)

line1, = axes.plot(dates,yvalues, lw=2, marker='*', color='r')
axes.legend([line1],['VALUES'],loc=1)
axes.grid()
axes.set_xlabel('YEAR')
axes.set_ylabel('VALUES')

yticks = [-2.0,-1.75,-1.5,-1.25,-1.0,-0.75,-0.5,-0.25,0.0]
axes.set_yticks(yticks)
axes.set_yticklabels(["$%.2f$" % y for y in yticks]);

axes.set_xticks(dates)
#axes.set_xticklabels()

这个数字看起来不错.但是无法正确标记x轴刻度线.我正在尝试使用类似2007-01-02或2007年1月的标签来标记x轴.

The figure seems good. But unable to label the x axis ticks correctly. I am trying to label x axis with something like 2007-01-02 or 2007 Jan.

预先感谢

推荐答案

您可以使用

You can control the format of the dates using a DateFormater:

import matplotlib.dates as mdates
xfmt = mdates.DateFormatter('%Y-%m-%d')
axes.xaxis.set_major_formatter(xfmt)

<小时>

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

year = [20070102,20070806,20091208,20111109,20120816,20140117,20140813]
yvalues = [-0.5,-0.5,-0.75,-0.75,-0.5,-1.25,-1.25]

dates = [DT.datetime.strptime(str(int(date)),'%Y%m%d') for date in year]

fig, axes = plt.subplots(1, 1, figsize=(16, 9), dpi=100)

line1, = axes.plot(dates,yvalues, lw=2, marker='*', color='r')
axes.legend([line1],['VALUES'],loc=1)
axes.grid()
axes.set_xlabel('YEAR')
axes.set_ylabel('VALUES')

yticks = [-2.0,-1.75,-1.5,-1.25,-1.0,-0.75,-0.5,-0.25,0.0]
axes.set_yticks(yticks)
axes.set_yticklabels(["$%.2f$" % y for y in yticks]);

xfmt = mdates.DateFormatter('%Y-%m-%d')
axes.xaxis.set_major_formatter(xfmt)
axes.set_xticks(dates)
plt.xticks(rotation=25)
plt.show()

收益

这篇关于如何在matplotlib中设置日期的xticklabels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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