简体   繁体   中英

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

I want to do two things:

  1. I want to format the x-axis to have quarters. My time series data is in quarters. So for example, for date 2012-12-31 I want it to show as 2012Q4, for 2013-03-31 as 2013Q1 , for 2013-03-30 as 2013Q2 and so on. I can use
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

to set the format. But I could not find a way to set it to quarters. pandas has Q, ( pandas format datetimeindex to quarters ) but that did not work here. How do I do this?

  1. I want the major tick locator to be at end of quarter. I could use this code (see below) to set it to 30th day of each month/quarter, but I cannot figure out how to set it to the last day of each month/quarter, since the quarter ending june ends on 30th while the quarter ending in march ends on 31st.
dayloc = mdates.MonthLocator(bymonth=(3,6,9,12),bymonthday=30)
ax.xaxis.set_major_locator(dayloc)

The complete code to generate the data as well as the plot is below:

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()

Try this instead, using pd.DataFrame.to_period and 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()

Output: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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