13
5

More than 5 years have passed since last update.

matplotlibで対数グラフを描くときの目盛り設定

Posted at

matplotlibで対数軸のグラフを描いているときに困ったことと解決策の記録です.

困ったこと

matplotlibで対数軸にプロットしたいときには,ax.set_xscale('log')と書くと思います.次のコードを実行すると確かに対数軸でプロットされます(下図).ただし,これではデフォルトで対数軸が$10^n$のかたちで表示されてしまいます.時と場合によっては,1, 10, 100...の方が良いこともあるので困ります.どうしたら変更できるのか調べました.

#coding: utf-8

import sys
import random
import math
import matplotlib.pyplot as plt

x = []
y = []

for i in range(100):
    x.append(10**random.uniform(0,4))
for i in range(len(x)):
    y.append(math.exp(-x[i]/10**2))

fig, ax = plt.subplots()
ax.plot(x, y,'.')
ax.set_xscale('log')
plt.show()

normal.png

解決策1

力技で解決してしまう方法です.目盛りの位置とそれに対応する目盛りの文字列を用意してあげます.面倒くさいですが,手っ取り早いとは思います.

#coding: utf-8

import sys
import random
import math
import matplotlib.pyplot as plt

x = []
y = []

for i in range(100):
    x.append(10**random.uniform(0,4))
for i in range(len(x)):
    y.append(math.exp(-x[i]/10**2))

fig, ax = plt.subplots()
ax.plot(x, y,'.')
ax.set_xscale('log')

############################################
pos = [1, 10, 100, 1000, 10000] 
ticks = ['1', '10', '100', '1000', '10000']
ax.set_xticks(pos)
ax.set_xticklabels(ticks)
############################################

plt.show()

solution1.png

解決策2

なんかよく分からないおまじないを書いたら解決できるやつです.おまじないは2行です.2つ目のax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())は,ax.set_xscale('log')の後に書かないと意味ないっぽいです.

import matplotlib.ticker
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
#coding: utf-8

import sys
import random
import math
import matplotlib.pyplot as plt

##########################################
import matplotlib.ticker
##########################################

x = []
y = []

for i in range(100):
    x.append(10**random.uniform(0,4))
for i in range(len(x)):
    y.append(math.exp(-x[i]/10**2))

fig, ax = plt.subplots()
ax.plot(x, y,'.')
ax.set_xscale('log')

#######################################################################
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
#######################################################################

plt.show()

norma2.png

参考にさせていただいたページ

- matplotlib によるデータ可視化の方法 (2)
- stackoverflow

13
5
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
13
5