I want to do two things:
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?
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()
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.