LoginSignup
32
29

More than 5 years have passed since last update.

matplotlibでよく使うコマンドまとめ

Posted at

IPython & matplotlib でグラフを書く時の細かい部分をよく忘れてしまうのでまとめました。
何番ぜんじだよって話ですが、ご参考になれば幸いです。

毎回使うモジュールのインポート

~/.ipython/profile_default/startup/の下に00_import.pyなどを作成しておくと
IPythonの起動時に自動で実行してくれる。

00_import.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import re

plotで線グラフを書く

よく使うのはこんなところではないでしょうか。

sample_1.py
x = np.arange(-10, 10, 0.1)
y = x**3

plt.figure(figsize=(6, 4))  # set aspect by width, height

plt.xlim(min(x), max(x))
plt.ylim(min(y), max(y))  # set range of x, y

plt.xticks(np.arange(min(x), max(x)+2, 2))
plt.yticks(np.arange(min(y), max(y)+200, 200))  # set frequency of ticks

plt.plot(x, y, color=(0, 1, 1), label='y=x**3')  # color can be set by (r, g, b) or text such as 'green'

plt.hlines(0, min(x), max(x), linestyle='dashed', linewidth=0.5)  # horizontal line
plt.vlines(0, min(y), max(y), linestyle='dashed', linewidth=0.5)  # vertical line

plt.legend(loc='upper left')  # location can be upper/lower/center/(none) and right/left/(none)
plt.title('Sample 1')
plt.show()

graph_sample1.png

第1軸と第2軸に分けて描く

これも必要なとき多いけど、毎回忘れていたので・・・。
axeオブジェクトを操作するときはplt.うんたらのときと比べて少しメソッド名が変わります(set_ が要る)
figureオブジェクトとaxeオブジェクトの関係は下のリンクがわかりやすいです。
http://ailaby.com/matplotlib_fig/

sample_2.py
# just prepare data
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = x

fig, ax = plt.subplots(figsize=(5,5))  # create figure and axes object
ax.plot(x, y1, label='sin(x)', color='red')  # plot with 1st axes

ax.set_ylabel('y=sin(x)')  # set label name which will be shown outside of graph
ax.set_yticks(np.arange(-1, 1+0.2, 0.2))

ax2 = ax.twinx()  # create 2nd axes by twinx()!
ax2.set_ylabel('y=x')
ax2.plot(x, y2, label='x', color='blue')  # plot with 2nd axes

ax.set_xlim(0, 5)  # set range

ax.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.title('Sample 2')
plt.show()

graph_sample2.png

文字入り散布図を描く

個人的には散布図の各点に番号とかスコアをアノテーションすることが多いのでそれを入れてます。

sample_3.py
pos_x = [1.0, 1.5, 2.1, 2.7, 3.0]  # x of positions
pos_y = [0.7, 0.9, 1.0, 1.3, 1.5]  # y of positions
time = [1, 2, 3, 4, 5]  # time of each positions

# draw points
plt.scatter(pos_x, pos_y, color='red', label='Position')

# annotate each points
for i, t in enumerate(time):
    msg = 't=' + str(t)
    plt.annotate(msg, (pos_x[i], pos_y[i]))  # x,y need brackets

plt.title('Sample 3')    
plt.legend(loc='upper left')
plt.show()

graph_sample3.png

おしまいです。
今後思いついたらまた追記させていただきます。それでは。

32
29
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
32
29