【matplotlib】軸ラベルを縦書きにしたい【python】

グラフを書くときに、スペースの関係で軸ラベルを縦書きにしたくなった。

色々調べたのでメモしておく。

まず普通にグラフを書くとこんな感じになる。

import numpy as np
import matplotlib.pyplot as plt
import japanize_matplotlib

y = np.array([1, 2, 3, 4])
fig = plt.figure(figsize=(4, 4))
ax1 = fig.add_subplot(111)
ax1.bar(y, y)
ax1.set_xlabel("x-axis", loc="left")

plt.show()

 



まず最初に考えたのがrotationで回転する方法。一番手っ取り早いのだが、横向きになってしまうので見づらく、これは縦書きとは言えない。

ax1.set_xticklabels(labels, rotation=90)

 

色々調べたが、いい感じに縦にする方法はなさそうだったので、不細工だが自力で1文字ごとに改行(\n)を挟むのがよさそうだとわかった。

labels = ['A\n-\n\n社', 'B\n-\n\n社', 'C\n-\n\n社', 'D\n-\n\n社'] 

 

ただし、このままだと横棒(-)の表示に違和感があるので、縦棒(|)に変える。

labels = ['A\n|\n\n社', 'B\n|\n\n社', 'C\n|\n\n社', 'D\n|\n\n社'] 

 

これで満足。これを汎用的に使えるように、ラベルを縦書きにする関数(tategaki)を定義して完成。

import numpy as np
import matplotlib.pyplot as plt
import japanize_matplotlib

y = np.array([1, 2, 3, 4])#データ
labels = ['A-会社', 'B-会社', 'C-会社', 'D-会社']#x軸のラベル
ind = np.arange(len(y)) #要素の数

#x軸ラベルを縦書きに変換するコード
def tategaki(labels):
    new_labels = []
    for n in labels:
        n2 = '\n'.join(n.replace("-", "|"))#"-"を"|"に置換して、一文字ごとに"\n"を挟む
        new_labels.append(n2)
    return new_labels

new_labels = tategaki(labels)#新しいx軸のラベル

fig = plt.figure(figsize=(4, 4))
ax1 = fig.add_subplot(111)
ax1.bar(ind, y)
ax1.set_xticks(ind)
ax1.set_xticklabels(new_labels)

plt.show()