import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
#Sample data
data = pd.DataFrame({'MAU':np.random.randint(5000, 8500,(10,))},
index=pd.date_range('2019/12/25', freq='d', periods=10))
MAU | |
---|---|
2019-12-25 | 6831 |
2019-12-26 | 6829 |
2019-12-27 | 5477 |
2019-12-28 | 8204 |
2019-12-29 | 8227 |
2019-12-30 | 6257 |
2019-12-31 | 5828 |
2020-01-01 | 5868 |
2020-01-02 | 5355 |
2020-01-03 | 5548 |
fig = plt.figure(figsize=(4,3), dpi=144)
ax = fig.add_subplot(111)
ax.bar(data.index, data['MAU'])
ax.set_xticklabels(data.index, rotation=45)
plt.tight_layout()
plt.savefig('test01.svg')
plt.show()
#Looks great with Locator and formatter
fig = plt.figure(figsize=(4,3), dpi=144)
ax = fig.add_subplot(111)
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.bar(data.index, data['MAU'])
plt.savefig('test02.svg')
plt.show()
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
fmt = []
yy = ''
for x in data.index:
years = x.year
days = x.day
if yy != x.year:
fmt.append(str(days)+'\n'+str(years))
else:
fmt.append(str(days))
yy = x.year
fig = plt.figure(figsize=(4,3), dpi=144)
ax = fig.add_subplot(111)
ax.set_xticklabels(fmt)
ax.bar(data.index, data['MAU'])
plt.savefig('test03.png')
plt.show()
FixedFormatter
with the matplotlib formatter.fig = plt.figure(figsize=(4,3), dpi=144)
ax = fig.add_subplot(111)
# positions = [0,1,2,3,4,5,6,7,8,9]
labels = ['Dec\n2019','26','27','28','29','30','31','Jan\n2020','2','3']
# ax.xaxis.set_major_locator(ticker.FixedLocator(positions))
ax.xaxis.set_major_formatter(ticker.FixedFormatter(labels))
ax.bar(data.index, data['MAU'])
plt.savefig('test04.png')
plt.show()
FuncFormatter
with the matplotlib formatter.#matplotlib uses the Gregorian calendar
fig = plt.figure(figsize=(4,3), dpi=144)
ax = fig.add_subplot(111)
YY = ''
@ticker.FuncFormatter
def major_fmt(x, pos):
global YY
y = mdates.num2date(int(x)).year
d = mdates.num2date(int(x)).day
if YY != y:
t = '{}\n{}'.format(d, y)
else:
t = '{}'.format(d)
YY = y
return t
ax.xaxis.set_major_formatter(major_fmt)
ax.bar(data.index, data['MAU'])
plt.savefig('test05.png')
plt.show()
num2date (int (x))
.[Matplotlib] Official Website
Formatter
of Matplotlib
.Recommended Posts