如何更改matplotlib图的日期时间刻度标签频率? [英] How to change the datetime tick label frequency for matplotlib plots?

查看:468
本文介绍了如何更改matplotlib图的日期时间刻度标签频率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面显示的是模拟数据图,其中包含我要修改的xtick。默认情况下,pd.df.plot选择大约间隔3个月的日期作为刻度。但是我想要的是每个月都在变动。做这个的最好方式是什么?那季节tick呢?先感谢您。

Below shows a plot of simulated data, which contains the xticks that I want to modify. By default, the pd.df.plot chooses dates that are approximately 3 months apart as ticks. But what I want is each month being a tick. What is the best way to do this? What about seasonal ticks? Thank you in advance.

推荐答案

首先,您必须将熊猫日期对象转换为python日期对象。由于matplotlib内部日期转换功能,因此需要进行此转换。然后使用 matplotlib.dates 中的函数设置所需的格式化程序和刻度位置,如下所示:

First of all you have to convert pandas date objects to python date objects. This conversion is needed because of matplotlib internal date conversion functions. Then use functions from matplotlib.dates to set desired formatter and tick positions like here:

import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates

# convert date objects from pandas format to python datetime
index = pd.date_range(start = "2015-07-01", end = "2017-01-01", freq = "D")
index = [pd.to_datetime(date, format='%Y-%m-%d').date() for date in index]
data = np.random.randint(1,100, size=len(index))
df = pd.DataFrame(data=data,index=index, columns=['data'])
print (df.head())

ax = df.plot()
# set monthly locator
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
# set formatter
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
# set font and rotation for date tick labels
plt.gcf().autofmt_xdate()

plt.show()

对于季节标签自己构造它,然后使用 plt.setp 函数进行设置(对于02月份,设置标签 winter ,04- spring 等):
plt.setp(new_labels,rotation = 90,fontsize = 9)

For season labels you have to construct it by yourself and then set it with plt.setp function (for month 02 set label winter, 04 - spring etc.): plt.setp(new_labels, rotation=90, fontsize=9).

df头:

            data
2015-07-01    26
2015-07-02    33
2015-07-03    46
2015-07-04    69
2015-07-05    17

这篇关于如何更改matplotlib图的日期时间刻度标签频率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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