「.NET 開発基盤部会 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。
目次 †
概要 †
Matplotlib(マットプロットリブ)は二次元の平面にグラフを描画するライブラリ
- オブジェクト指向のAPIを提供しており、様々な種類のグラフを描画する能力を持つ。
- 描画できるのは主に2次元のプロットだが、3次元プロットの機能も追加されてきている。
- BSDスタイルのライセンスの下で配布されている。
準備 †
インストール †
matplotlib †
>pip install matplotlib
seaborn †
matplotlibラッパ
>pip install seaborn
インポート †
別名 †
numpyも一緒にインポート
>>>import numpy as np
>>>import matplotlib.pyplot as plt
>>>import seaborn as sns
jupyter上で利用するとき †
>>>%matplotlib inline
ファースト・ステップ †
ヒストグラム †
データの生成 †
- 階層別表示の例
y=[0,1,2]
# valのベクトルを生成し、n行1列の2次元配列(行列)化
y[0]=np.random.normal(50, 10, 1000).reshape(-1, 1) # 平均50・標準偏差10のデータ1000個
y[1]=np.random.normal(150, 20, 1000).reshape(-1, 1) # 平均150・標準偏差20のデータ1000個
y[2]=np.random.normal(100, 30, 1000).reshape(-1, 1) # 平均100・標準偏差30のデータ1000個
# clsのベクトルを生成し、n行1列の2次元配列(行列)化して、valとclsを結合(n行2列の2次元配列(行列)
y[0]=np.hstack([y[0], np.full(1000, 0).reshape(-1, 1)])
y[1]=np.hstack([y[1], np.full(1000, 1).reshape(-1, 1)])
y[2]=np.hstack([y[2], np.full(1000, 2).reshape(-1, 1)])
# numpy.ndarray(行列)をDataFrame化
y[0]=pd.DataFrame(y[0],columns=['val','cls'])
y[1]=pd.DataFrame(y[1],columns=['val','cls'])
y[2]=pd.DataFrame(y[2],columns=['val','cls'])
# 3つのclsのDataFrameを結合
df=y[0]
df=pd.concat([df,y[1]],axis=0)
df=pd.concat([df,y[2]],axis=0)
# インデックス再設定
df.index=np.arange(len(df))
データの可視化 †
- 階層別表示の例
cls列の値(階層)毎にグループ分けしてval値をヒストグラムで可視化
for _class, _color in zip([1,2,3], ['r','g','b']):
plt.hist(df[df.cls==_class]['val'], bins=round(bins), alpha=0.3, color=_color)
plt.show()
散布図 †
データの生成 †
線形単回帰している風のデータを生成する。
- データ1
>>>np.random.seed(0) # 乱数生成器の状態を指定
>>>x1=np.random.normal(50,10,100) # 平均50 標準偏差10の正規分布データ100個
>>>y1=x1+np.random.normal(0,10,100) # 線形単回帰している風のxに対応するyの値
>>>x2
...見ても解らん数字の羅列...
>>>y2
...見ても解らん数字の羅列...
- データ2
より、相関係数が大きい感じのデータ。
>>>np.random.seed(0) # 乱数生成器の状態を指定
>>>x2=np.random.normal(30,10,100) # 平均30 標準偏差10の正規分布データ100個
>>>y2=2*x2+np.random.normal(0,10,100) # 線形単回帰している風のxに対応するyの値
>>>x2
...見ても解らん数字の羅列...
>>>y2
...見ても解らん数字の羅列...
データの可視化 †
- 可視化
>>>plt.scatter(x,y)
>>>plt.title('グラフのタイトル')
>>>plt.xlabel('x軸のラベル')
>>>plt.ylabel('y軸のラベル')
>>>plt.xticks(np.arange(下限,上限,間隔))
>>>plt.yticks(np.arange(下限,上限,間隔))
>>>plt.grid() # グリッド線を表示
>>>plt.show()
- 修飾を加えた例
>>>plt.scatter(x1,y1)
>>>plt.title('title')
>>>plt.xlabel('xlabel')
>>>plt.ylabel('ylabel')
>>>plt.xticks(np.arange(0,100,10))
>>>plt.yticks(np.arange(0,100,10))
>>>plt.grid() # グリッド線を表示
>>>plt.show()
- 2つのデータ群
>>>plt.scatter(x1,y1,color='red',marker='x',label='data1')
>>>plt.scatter(x2,y2,color='blue',marker='+',label='data2')
>>>plt.title('title')
>>>plt.xlabel('xlabel')
>>>plt.ylabel('ylabel')
>>>plt.legend(loc='upper right') # 凡例位置
>>>plt.xticks(np.arange(0,100,10))
>>>plt.yticks(np.arange(0,100,10))
>>>plt.grid() # グリッド線を表示
>>>plt.show()
三次関数グラフ †
データの生成 †
コチラは関数なので、式(y=x^3+x^2x+x+1)からデータを生成する感じ。
>>>#x座標
>>>x=np.arange(-10,10,0.1) # -10 - +10まで0.1刻みの配列
>>>#x座標
>>>y=0.01*(x**3+x**2+x+1) # 三次関数:y=x^3+x^2x+x+1
データの可視化 †
グラフのプロット
- 修飾を加えた例
前述の修飾項目を除く
>>>plt.plot(x,y) # グラフをプロットする
>>>plt.hlines([0], -10, 10, linestyles='dashed', color='gray') # x軸に平行な直線を表示
>>>plt.vlines([0], -1, 1, linestyles='dashed', color='gray') # y軸に平行な直線を表示
>>>plt.xlim([-5, 5]) # x軸方向の表示範囲を指定
>>>plt.ylim([-1, 1]) # y軸方向の表示範囲を指定
>>>plt.show() # グラフを表示する
三角関数グラフ †
sin関数グラフ †
sin関数からデータを生成する。
- データの生成
>>>#x座標
>>>x=np.arange(0,6,0.1) # 0 - 6まで0.1刻みの配列
>>>x
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ,
1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1,
2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2,
3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4. , 4.1, 4.2, 4.3,
4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5. , 5.1, 5.2, 5.3, 5.4,
5.5, 5.6, 5.7, 5.8, 5.9])
>>>#y座標
>>>y=np.sin(x)
>>>y
array([ 0. , 0.09983342, 0.19866933, 0.29552021, 0.38941834,
0.47942554, 0.56464247, 0.64421769, 0.71735609, 0.78332691,
0.84147098, 0.89120736, 0.93203909, 0.96355819, 0.98544973,
0.99749499, 0.9995736 , 0.99166481, 0.97384763, 0.94630009,
0.90929743, 0.86320937, 0.8084964 , 0.74570521, 0.67546318,
0.59847214, 0.51550137, 0.42737988, 0.33498815, 0.23924933,
0.14112001, 0.04158066, -0.05837414, -0.15774569, -0.2555411 ,
-0.35078323, -0.44252044, -0.52983614, -0.61185789, -0.68776616,
-0.7568025 , -0.81827711, -0.87157577, -0.91616594, -0.95160207,
-0.97753012, -0.993691 , -0.99992326, -0.99616461, -0.98245261,
-0.95892427, -0.92581468, -0.88345466, -0.83226744, -0.77276449,
-0.70554033, -0.63126664, -0.55068554, -0.46460218, -0.37387666])
sin, cos関数グラフ †
同様に、sin, cos関数からデータを生成する。
- データの描画
>>>#グラフ描画
>>> plt.plot(x,y1, label="sin")
>>> plt.plot(x,y2, linestyle="--", label="cos")
>>> plt.xlabel("x")
>>> plt.ylabel("y")
>>> plt.title("sin & cos")
>>> plt.legend()
>>> plt.show()
セカンド・ステップ †
パレート図 †
結構手数が要る。
散布図行列 †
matplotlibラッパであるseabornを使って、
表の全ペアのヒストグラムと散布図を表示。
データの生成 †
- 生成
dfは数値表として初期化されたDataFrame
from sklearn import datasets
iris = datasets.load_iris()
df_data = pd.DataFrame(iris.data, columns=iris.feature_names)
df_target = pd.DataFrame(iris.target, columns=['species'])
df = pd.concat([df_data, df_target], axis=1)
df.head()
データの描画 †
ヒートマップ †
データの生成 †
dfは数値表として初期化されたDataFrame。
# 10x12 の一様乱数を生成
np.random.seed(0)
uniform_data = np.random.rand(10, 12)
データの描画 †
# 図表のサイズを指定
plt.figure(figsize=(10, 7))
# numpy.ndarray(行列)でもDataFrameでもOK
# annot : 数値を表示するかどうか(annotation)
# square: 四角を正方形に合わせるかどうか
# fmt : 表示する数値の形式(formatting)
sns.heatmap(uniform_data, annot=True, square=True, fmt='.2f')
plt.show()
サード・ステップ(その他) †
画像の表示 †
>>>from matplotlib.image import imread
>>>img=imread('C:\Windows\Web\Wallpaper\Theme1\img1.jpg')
>>>plt.imshow(img)
>>>plt.show()
3次元のプロット †
準備 †
インポート
# import
from mpl_toolkits.mplot3d import Axes3D
追加 †
- 点
# (x, y, z)
x = np.random.rand(50)
y = np.random.rand(50)
z = np.random.rand(50)
# 図表の定義
fig = plt.figure()
#ax = Axes3D(fig)
ax = fig.add_subplot(projection='3d')
# 3Dでプロット
ax.scatter(x, y, z)
# ラベル
ax.set_xlabel('X-label')
ax.set_ylabel('Y-label')
ax.set_zlabel('Z-label')
- 直線
# (x, y, z)
x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
z = [1, 2, 3, 4, 5]
# 図表の定義
fig = plt.figure()
#ax = Axes3D(fig)
ax = fig.add_subplot(projection='3d')
# 3Dでプロット
ax.plot(x, y, z, "o-")
# ラベル
ax.set_xlabel('X-label')
ax.set_ylabel('Y-label')
ax.set_zlabel('Z-label')
- 曲線
# (x, y, z)
x = np.linspace(0, 8 * np.pi, num=50)
y = x * np.cos(x)
z = x * np.sin(x)
# 図表の定義
fig = plt.figure()
#ax = Axes3D(fig)
ax = fig.add_subplot(projection='3d')
# 3Dでプロット
ax.plot(x, y, z, "o-")
# ラベル
ax.set_xlabel('X-label')
ax.set_ylabel('Y-label')
ax.set_zlabel('Z-label')
- 平面
# (x, y, z)
# 2次元のグリッド座標
x, y = np.meshgrid(np.arange(0, 40, 2.5), np.arange(1, 10, 0.5))
# 平面の式
z = 2*x + 3*y + 4
# 図表の定義
fig = plt.figure()
#ax = Axes3D(fig)
ax = fig.add_subplot(projection='3d')
# 3Dでプロット
ax.plot_wireframe(x,y,z)
# ラベル
ax.set_xlabel('X-label')
ax.set_ylabel('Y-label')
ax.set_zlabel('Z-label')
- 曲面
# (x, y, z)
# 2次元のグリッド座標
x, y = np.meshgrid(np.arange(-3, 3, 0.25), np.arange(-3, 3, 0.25))
# 曲面の式
z = np.sin(x)+ np.cos(y)
# 図表の定義
fig = plt.figure()
#ax = Axes3D(fig)
ax = fig.add_subplot(projection='3d')
# 3Dでプロット
ax.plot_wireframe(x,y,z)
# ラベル
ax.set_xlabel('X-label')
ax.set_ylabel('Y-label')
ax.set_zlabel('Z-label')
参考 †
|