複数のplt.textで重なる文字をなんとかできる。


複数のplt.textで重なる文字をなんとかしたい。

plt.textをfor文で何個も付けていると文字同士が重なり読めなくなってしまう…

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)
x, y = np.random.random((2,30))
fig, ax = plt.subplots()
plt.plot(x, y, 'bo')
texts = [plt.text(x[i], y[i], 'Text%s' %i, ha='center', va='center') for i in range(len(x))]

そんなお困りを解決してくれる嬉しいライブラリがあったので共有します

adjustTextを入れるだけ

このライブラリはR/ggplot2のggrepel packageに影響を受けて作られたそうです。
(Rの方は知りません)
導入はpipでできます

pip install adjustText

使い方も簡単で、adjustTextのadjust_textに整列したいtextsをリストにして入れるだけ

from adjustText import adjust_text

fig, ax = plt.subplots()
plt.plot(x, y, 'bo')
texts = [plt.text(x[i], y[i], 'Text%s' %i, ha='center', va='center') for i in range(len(x))]
adjust_text(texts)

どの点のアノテーションかわかりやすいようにplt.annotateのような矢印を入れることも可能。

fig, ax = plt.subplots()
plt.plot(x, y, 'bo')
texts = [plt.text(x[i], y[i], 'Text%s' %i, ha='center', va='center') for i in range(len(x))]
adjust_text(texts, arrowprops=dict(arrowstyle='->', color='red'))

ありがてえ!!!

参考