User Tools

Site Tools


python:matplotlib:基本的な使い方

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Next revision Both sides next revision
python:matplotlib:基本的な使い方 [2018/01/20 22:22]
koudai
python:matplotlib:基本的な使い方 [2018/01/20 23:17]
koudai
Line 10: Line 10:
 ===== 初めてのプロット ===== ===== 初めてのプロット =====
  
-とりあえず何か書いてみましょう。+とりあえずsin関数を書いてみましょう。
 次のスクリプトを作成します。 次のスクリプトを作成します。
  
Line 41: Line 41:
  
 plt.plot(x, y) plt.plot(x, y)
-plt.savefig("sin.png"  # プロットしたグラフを画面表示する+plt.savefig("sin.png"  # プロットしたグラフをファイルsin.png保存する
 </file> </file>
  
Line 73: Line 73:
 x = np.arange(-np.pi, np.pi, 0.1) x = np.arange(-np.pi, np.pi, 0.1)
 y = np.sin(x) y = np.sin(x)
-plt.title("graph"      # グラフのタイトル +plt.title("graph"  # グラフのタイトル 
-plt.xlabel(r"$x$"      # x軸(横軸)のラベル +plt.xlabel("x"     # x軸(横軸)のラベル 
-plt.ylabel(r"$\sin x$" # y軸(縦軸)のラベル+plt.ylabel("sin x" # y軸(縦軸)のラベル
  
 plt.plot(x, y) plt.plot(x, y)
Line 83: Line 83:
 {{:python:matplotlib:intro2.png?direct&400|}} {{:python:matplotlib:intro2.png?direct&400|}}
  
-TeXがインスールされて場合は二重引用符rをつけることでTeX機能使えます。 + 
-入っていない場合は <nowiki>plt.xlabel("x")</nowikiなどとしてください。+===== 複数のグラフ ===== 
 + 
 +複数のグラフを同時にプロッしたい場合を扱います。 
 +例えばsin関数とcos関数を同時にプロットしたい場合は、次ようします。 
 +どっちのグラフがどっちの関数かわからなくなるので凡例(legend)をつけます。 
 + 
 +<file python sin.py> 
 +import numpy as np 
 +import matplotlib.pyplot as plt 
 + 
 +x = np.arange(-np.pi, np.pi, 0.1) 
 +y1 = np.sin(x) 
 +y2 = np.cos(x) 
 + 
 +plt.title("graph"
 +plt.xlabel("x"
 +plt.ylabel("y"
 + 
 +plt.plot(x, y1, label="sin x"  # labelに凡例に表示す文字を指定 
 +plt.plot(x, y2, label="cos x") 
 +plt.legend()                     # 凡例を表示 
 + 
 +plt.show() 
 +</file> 
 + 
 +{{:python:matplotlib:intro3.png?direct&400|}} 
 + 
 +凡例表示する位置は、matplotlib適切な位置を自動的に探します。 
 +手動で設定する場合は、例えば左上の場合は <file python>plt.legend(loc="upper left")</file>とします。 
 +(右下の場合は lower right とします。他も同様) 
 + 
 + 
 +===== プロット範囲の指定 ===== 
 + 
 +matplotlibでは、そのままプロットするとすべのデータが枠内に収まるようにプロットれます。 
 +プロットした範囲を制限する場合は次のようにします 
 + 
 +<file python sin.py> 
 +import numpy as np 
 +import matplotlib.pyplot as plt 
 + 
 +x = np.arange(-2.0 * np.pi, 2.0 * np.pi, 0.1)  # -2πから2πまでのxを用意  
 +y1 = np.sin(x) 
 +y2 = np.cos(x) 
 + 
 +plt.title("graph"
 +plt.xlabel("x"
 +plt.ylabel("y"
 + 
 +plt.plot(x, y1, label="sin x") 
 +plt.plot(x, y2, label="cos x") 
 +plt.legend() 
 + 
 +plt.xlim(-np.pi, np.pi)   # x軸は-πからπまで 
 +plt.ylim(-1.2,   1.2)     # y軸は-1.2から1.2まで 
 + 
 +plt.show() 
 +</file> 
 + 
 +{{:python:matplotlib:intro4.png?direct&200|}} 
  
  
python/matplotlib/基本的な使い方.txt · Last modified: 2021/06/27 22:04 (external edit)