如何更改 matplotlib 图的日期时间刻度标签频率?
下面显示了一张模拟数据图,其中包含我想要修改的 xticks.默认情况下,pd.df.plot 选择相隔大约 3 个月的日期作为刻度.但我想要的是每个月都是一个滴答声.做这个的最好方式是什么?季节性蜱虫呢?先感谢您.
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.
首先,您必须将 Pandas 日期对象转换为 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