「.NET 開発基盤部会 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。
Matplotlib(マットプロットリブ)は二次元の平面にグラフを描画するライブラリ
>pip install matplotlib
matplotlibラッパ
>pip install seaborn
numpyも一緒にインポート
>>>import numpy as np >>>import matplotlib.pyplot as plt >>>import seaborn as sns
>>>%matplotlib inline
x = np.random.normal(70, 10, 1000) # 平均70・標準偏差10のデータ1000個
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))
>>>plt.hist(x) >>>plt.show()
>>>import math >>>bins = math.log(len(x), 2) + 1 >>>plt.hist(x, bins=round(bins)) >>>plt.show()
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()
線形単回帰している風のデータを生成する。
>>>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 ...見ても解らん数字の羅列...
>>>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()
color='blue'
marker='x'
label='data x'
>>>plt.legend(loc='upper right') # 凡例位置
>>>plt.scatter(x1,y1) >>>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()
>>>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.show() # グラフを表示する
>>>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関数からデータを生成する。
>>>#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])
>>>#グラフ描画 >>>plt.plot(x,y) >>>plt.show()
同様に、sin, cos関数からデータを生成する。
>>>#x座標 >>>x=np.arange(0,6,0.1) # 0 - 6まで0.1刻みの配列 >>>#y座標 >>>y1=np.sin(x) >>>y2=np.cos(x)
>>>#グラフ描画 >>> 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を使って、
表の全ペアのヒストグラムと散布図を表示。
>pip install scikit-learn
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()
>>>sns.pairplot(df, height=2.0) >>>plt.show()
# 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()
インポート
# 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')