带日期的 Matplotlib - 更改每月数据的标签和刻度 [英] Matplotlib with dates - changing labels and ticks for monthly data

查看:37
本文介绍了带日期的 Matplotlib - 更改每月数据的标签和刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框:

  data_ = list(范围(106))index_ = pd.period_range('3/1/2004', '12/1/2012', freq='M')df2_ = pd.DataFrame(数据=数据_,索引=索引_,列= ['数据'])

我想绘制这个数据框.目前,我正在使用:

df2_.plot()

现在我喜欢控制 x 轴上的标签(可能还有刻度).特别是,我喜欢在轴上有每月的刻度,并且可能每隔一个月或每季度有一个标签.我也喜欢垂直网格线.

我开始查看

I have a dataframe like this:

data_ = list(range(106))
index_ =  pd.period_range('3/1/2004', '12/1/2012', freq='M')
df2_ = pd.DataFrame(data = data_, index = index_, columns = ['data'])

I want to plot this dataframe. Currently, I am using:

df2_.plot()

Now I like to control the labels (and possibly ticks) at the x axis. In particular, I like to have monthly ticks at the axis and possibly a label at every other month or quarterly labels. I also like to have vertical grid lines.

I started looking at this example but I am already failing at constructing the timedelta.

解决方案

With regards to constructing the timedelta, datetime.timdelta() doesn’t have a parameter to specify months, so it’s probably convenient to stick to pd.date_range(). However, I found that objects of type pandas.tslib.Timestamp don’t play nice with matplotlib ticks so you could convert them to datetime.date objects like so

index_ = [pd.to_datetime(date, format='%Y-%m-%d').date() 
        for date in pd.date_range('2004-03-01', '2012-12-01', freq="M")]

It’s possible to add gridlines and customise axes labels by first defining a matplotlib axes object, and then passing this to DataFrame.plot()

ax = plt.axes()
df2_.plot(ax=ax)

Now you can add vertical gridlines to your plot

ax.xaxis.grid(True)

And specify quarterly xticks labels by using matplotlib.dates.MonthLocator and setting the interval to 3

ax.xaxis.set_major_locator(dates.MonthLocator(interval=3))

And finally, I found the ticks to be to be very crowded so I formatted them to get a nicer fit

ax.xaxis.set_major_formatter(dates.DateFormatter('%b %y'))
labels = ax.get_xticklabels()
plt.setp(labels, rotation=85, fontsize=8)

To produce the following:

这篇关于带日期的 Matplotlib - 更改每月数据的标签和刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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