LoginSignup
11
12

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-06-03

複数の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))]

wiki_example_before.png

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

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)

wiki_example_after_no_arrows.png

どの点のアノテーションかわかりやすいように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'))

wiki_example_after_with_arrows.png

ありがてえ!!!

参考

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12