LoginSignup
20
23

More than 5 years have passed since last update.

matplotlibで枠線を消したグラフをつくる

Last updated at Posted at 2017-01-30

こんな感じのグラフをmatplotlibでつくる方法。

スクリーンショット 2017-01-30 21.17.49.jpg

matplotlibのインポート

まずはmatplotlibをpltの名前でインポート。
使ったバージョンはPython3.5とmatplotlib 1.5.3。matplotlib 2.0でも動くはず。

matplotlibのインポート
import matplotlib.pyplot as plt

普通にプロット

とりあえずプロット
plt.plot([0,10,20,30,40,50], [10,20,30,5,25,30])
plt.show()

matplotlibのデフォルトデザインである上下左右に枠線がついたグラフが作図される。
スクリーンショット 2017-01-30 21.08.22.jpg

右と上の枠線を消す

plt.gca()からspinesを呼び出すことで枠線を操作できる。'right''left''top''bottom'でそれぞれ対応する枠線を操作できる。操作したい枠線を指定してset_visible(False)で枠線を消すことができる。しかし,枠線は消えたが目盛りが消えない。

右と上の枠線を消す
plt.plot([0,10,20,30,40,50], [10,20,30,5,25,30])
plt.gca().spines['right'].set_visible(False)
plt.gca().spines['top'].set_visible(False)
plt.show()

スクリーンショット 2017-01-30 21.10.39.jpg

右と上の目盛りを消す

同じくplt.gca()からyaxis.set_ticks_position()で指定した目盛りのみを表示させる。今回は左と下の目盛りを残したいので'left''bottom'を指定。

右と上の目盛りを消す
plt.plot([0,10,20,30,40,50], [10,20,30,5,25,30])
plt.gca().spines['right'].set_visible(False)
plt.gca().spines['top'].set_visible(False)
plt.gca().yaxis.set_ticks_position('left')
plt.gca().xaxis.set_ticks_position('bottom')
plt.show()

スクリーンショット 2017-01-30 21.17.49.jpg

デフォルトで枠線を消した状態にする

matplotlibrcをいじることで枠線なしのグラフをデフォルトのグラフとして設定することができる。
macの場合は~/.matplotlib/matplotlibrc の設定ファイルを開く。HomebrewでPythonをインストールした場合は,/usr/local/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc にある。

matplotlibrc中にこのような箇所があるので,#を削除してTrueをFalseに書き換える。

# axes.spines.left   : True   # display axis spines
# axes.spines.bottom : True
# axes.spines.top    : True
# axes.spines.right  : True

今回は上と右の枠線を消したいので,.topと.rightの#を削除してTrueをFalseに書き換える。

# axes.spines.left   : True   # display axis spines
# axes.spines.bottom : True
axes.spines.top    : False
axes.spines.right  : False

これで右と上の枠線が消えたグラフがデフォルトで出力される。

20
23
2

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
20
23