繁体   English   中英

Python Matplotlib (1) 将 x 轴标签格式化为 Year-Quarter 和 (2) 将 major_locator 设置为月末

[英]Python Matplotlib (1) format x-axis labels to Year-Quarter and (2) set major_locator to end of month

我想做两件事:

  1. 我想将 x 轴格式化为四分之一。 我的时间序列数据以季度为单位。 例如,对于日期 2012-12-31,我希望它显示为 2012Q4,对于 2013-03-31 为 2013Q1,对于 2013-03-30 为 2013Q2 等等。 我可以用
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

设置格式。 但是我找不到将其设置为四分之一的方法。 pandas 有 Q, ( pandas format datetimeindex to quads ) 但这在这里不起作用。 我该怎么做呢?

  1. 我希望主要刻度定位器位于季度末。 我可以使用此代码(见下文)将其设置为每个月/季度的第 30 天,但我不知道如何将其设置为每个月/季度的最后一天,因为截至 6 月的季度在 30 日结束,而3 月结束的季度于 31 日结束。
dayloc = mdates.MonthLocator(bymonth=(3,6,9,12),bymonthday=30)
ax.xaxis.set_major_locator(dayloc)

生成数据和绘图的完整代码如下:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
from datetime import timedelta

from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

dti = pd.date_range('2012-12-31', periods=30, freq='Q')
s1 = pd.Series(range(30),index=dti)
s2 = pd.Series(np.random.randint(100,1000,size=(30)),index=dti)

df = s2.to_frame(name='count')
print(df)
f1 = plt.figure("Quarterly",figsize=(10,5))
ax = plt.subplot(1,1,1)
dayloc = mdates.MonthLocator(bymonth=(3,6,9,12),bymonthday=30)
ax.xaxis.set_major_locator(dayloc)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

y= [datetime.date(t) for t in df.index]
z= [datetime.date(t).replace(day=1)+timedelta(days=0) for t in df.index]
widths = [t1-t0-timedelta(days=0) for t0,t1 in zip(z,y)]

ax.bar(y,df['count'],width=widths)
plt.setp(ax.get_xticklabels(), rotation=90)
f1.tight_layout()
f1.show()
input()

试试这个,使用pd.DataFrame.to_period和 pandas plot:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
from datetime import timedelta
%matplotlib inline

from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

dti = pd.date_range('2012-12-31', periods=30, freq='Q')
s1 = pd.Series(range(30),index=dti)
s2 = pd.Series(np.random.randint(100,1000,size=(30)),index=dti)

df = s2.to_frame(name='count')
df = df.to_period(freq='Q')
print(df)
f1 = plt.figure("Quarterly",figsize=(10,5))
ax = plt.subplot(1,1,1)
# dayloc = mdates.MonthLocator([3,6,9,12])
# ax.xaxis.set_major_locator(dayloc)
# ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

# y= [datetime.date(t) for t in df.index]
# z= [datetime.date(t).replace(day=1)+timedelta(days=0) for t in df.index]
# widths = [t1-t0-timedelta(days=0) for t0,t1 in zip(z,y)]

# ax.bar(y,df['count'],width=widths)
df.plot.bar(ax=ax)
plt.setp(ax.get_xticklabels(), rotation=90)
f1.tight_layout()

输出: 在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM