LoginSignup
5
6

More than 5 years have passed since last update.

備忘録@Python ORセミナー: matplotlib

Posted at

matplotlib

>>> import pylab as plt
>>> from pylab import * # 楽だけどあまり良くないパターン

データの用意

>>> x = plt.linspace(0, 2 * math.pi, 50) # 0-2*πの区間を50等分した配列
>>> y = plt.sin(x)

グラフで表示

>>> p = plt.plot(x, y)
>>> plt.show() # ipython --pylabとかしてたら不要

オプション

>>> plt.plot(x, y, 'オプション')
文字列
'b'
'g'
'r'
'c' シアン
'm' マゼンタ
'y'
'k'
'w'
文字列 プロットの線
'-' 実線
'--' 破線
'-.' 一点鎖線 ー・ー
':' 点線
'.'
',' ピクセル
'o'
'v' 下向き三角形
'^' 上向き三角形
'<' 左向き三角形
'>' 右向き三角形
's' 正方形
'p' 五角形
'*'
などなど

凡例・ラベル

  • legend(): 凡例(線が何を示しているか)
  • xlabel(): x軸のラベル
  • ylabel(): y軸のラベル

もし日本語を使いたい場合は,FontPropertiesでフォントを予め指定しないといけない.

>>> plt.xlabel(u"abcdefg")
>>> plt.ylabel(u"fugafuga")
>>> plt.legend([p], ("hogehoge"))
# 日本語使いたい
>>> prop = matplotlib.font_manager.FontProperties(fname="フォントの絶対パス")
>>> plt.xlabel(u"ふがふが", fontproperties=prop)

グラフを並べる

一つの図で複数のグラフを並べたいとき.
意外に便利で使える.

  • subplot(): 引数でどこを編集するか指定
>>> plt.subplot(221) # 縦2段、横2列の1番目
>>> plt.plot(x, sin(x))
>>> plt.subplot(222)
>>> plt.plot(x, sin(-x))

作成した図を保存

作成したグラフを論文やスライドに載せるときに重宝する.

  • savefig(): 引数は保存するファイル名
    • .jpg, .png, .bmp, .eps, .svg, .pdf等が選択可能
>>> plt.savefig("hoge.png", transparent=True (or False) # 背景を透明にする(しない)

それ以外

基本的には上記で済むはず.でもたまに下のとかつかう.

ヒストグラム

>>> data = plt.normal(5, 3, 500) # 平均5,標準偏差3の正規乱数
>>> plt.hist(data, bins=30, color="red"); None

棒グラフ

>>> years = [str(i) for i in range(2005, 2014)]
>>> steps = plt.arange(len(years)) 
>>> sales = 100 + 40 * plt.rand(len(years))
>>> plt.bar(steps, sales, align="center", color="green")
>>> plt.xticks(steps, years); None

円グラフ

>>> rate_data = [0.3, 0.4, 0.2, 0.1]
>>> lbl = ["O", "A", "B", "AB"]
>>> ex = (0, 0.05, 0, 0)
>>> plt.axis("equal")
>>> plt.pie(rate_data, explode=ex, startangle=90, shadow=True, autopct="%1.1f%%", labels=lbl); None

画像の表示

>>> imagedata = array([
            [1,1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1,1],
            [1,1,0,1,1,1,1,0,1,1],
            [1,0,1,0,1,1,0,1,0,1],
            [1,1,1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1,1],
            [1,0,1,1,1,1,1,1,0,1],
            [1,1,0,1,1,1,1,0,1,1],
            [1,1,1,0,0,0,0,1,1,1],
            [1,1,1,1,1,1,1,1,1,1]
])
>>> plt.imshow(imagedata)

塗りつぶし

>>> y1 = sin(x) * cos(x)
>>> plt.plot(x, y1)
>>> y2 = -sin(x) * cos(x)
>>> plt.plot(x, y2)
>>> plt.fill_between(x, y1, y2, interpolate=True, alpha=0.3)

3次元プロット

#3次元プロットの例
>>> from mpl_toolkits.mplot3d import Axes3D
>>> x3d = rand(100)
>>> y3d = rand(100)
>>> z3d = rand(100)
>>> fig = figure()
>>> ax = fig.add_subplot(111, projection="3d")
>>> ax.scatter3D(x3d, y3d, z3d)
5
6
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
5
6