[Matplotlib] Do not tilt the axis label

Introduction

background

Sample data

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

Graph as usual

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()
test01.png

Was there such a convenience!

#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()
test02.png
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

I want to customize it a little more!

Create axis labels yourself

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()
test03.png

Try using 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()
test04.png

Try using 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()
test05.png

About locator and Formatter

[Matplotlib] Official Website

Summary

Recommended Posts

[Matplotlib] Do not tilt the axis label
When the axis and label overlap in matplotlib
Put the second axis in 2dhistgram of matplotlib
matplotlib: Replace the axis itself with another one.
Do not pass self to ProcessPoolExecutor in the class
2-axis plot with Matplotlib
What to do if the image is not displayed using matplotlib etc. in the Docker container
Do not omit __init__.py
python> link> dir_util.copy_tree ()> update = 1> Do not copy the acquired one?
What to do when Japanese is not displayed on matplotlib
The websocket of toio (nodejs) and python / websocket do not connect.