python

【python】グラフ化ライブラリMatplotlibの基本的な使い方

はじめに

pythonのグラフ化ライブラリMatplotlibの基本的な使い方を備忘録としてまとめます。

Matplotlibはグラフを描画できるオープンソースライブラリでpythonの基本的なグラフライブラリです。

さくっとデータの可視化を行うのに最も適しています。

ちなみに、インタラクティブにグラフを操作したい場合は、holoviewsなどのライブラリを使うことで直観的な操作ができます。

モジュールインポート

import matplotlib.pyplot as plt

#JupyterNotebookでインライン表示するための宣言
%matplotlib inline

JupyterNotebookでインライン表示するときは、%matplotlib inline を入れます。

グラフ化

データ作成

データの形式はリスト、numpyのndarray、pandasのDataframeなどが使用できます。

#データ作成
import numpy as np
y = np.random.randn(100)
x = np.arange(100)

yのnp.random.randnは乱数を生成しており、xのnp.arange(100)は整数で0から99までを生成しています。

散布図 plt.scatter

#散布図 plt.scatter
plt.scatter(x,y)
plt.show()
matplotlib_scatter

散布図の点の色とマーカー種類の変更

# marker "+" "^" "x" "s" "o" "*"
plt.scatter(x,y, c="red", marker="x")
plt.show
matplotlib_scatter_c_marker

折れ線グラフ plt.plot

#折れ線グラフ plt.plot
plt.plot(x,y)
plt.show()
matplotlib_plot

折れ線グラフの線の色、線の種類、線幅の変更

#線種 'dotted' 'dashdot' 'solid'
plt.plot(x, y, c="red", linestyle='dashdot', linewidth=2)
plt.show()
matplotlib_plot_color_linestyle_width

ヒストグラム plt.hist

plt.hist()でヒストグラムを描画できます。引数のbinsで棒の数を指定できます。指定しない場合は自動で描画されます。

#ヒストグラム plt.hist
plt.hist(y, bins=15)
plt.show()

画像のサイズを変更

plt.figure(figsize=(横インチ, 縦インチ), dpi=解像度)にてサイズと解像度を変更できます。

#画像のサイズを変更 
plt.figure(figsize=(10, 6), dpi=80)
plt.scatter(x,y)
plt.show()

タイトル、X軸ラベル・Y軸ラベル、罫線の追加

#タイトル、X軸ラベル・Y軸ラベル、罫線の追加
plt.title('Test Graph')    #タイトル
plt.xlabel('X Label')      #X軸ラベル
plt.ylabel('Y Label')      #Y軸ラベル
plt.grid()                 #罫線
plt.scatter(x,y)
plt.show()

凡例の追加

#凡例の追加
plt.scatter(x,y, label='Label1')
plt.scatter(x,y*2, label='Label2')
plt.legend()
plt.show()

グラフの複数配置(Pyplotインターフェースで簡易的に表示)

#グラフの複数配置
# 新規のウィンドウを描画
plt.figure(figsize=(10,8))

# 左上
plt.subplot(2,2,1)
plt.plot(x, y)

# 右上
plt.subplot(2,2,2)
plt.plot(x*2, y*2)

# 左下
plt.subplot(2,2,3)
plt.plot(x*3, y*3)

# 右下
plt.subplot(2,2,4)
plt.plot(x*4, y*4)

# グラフ間の間隔を調整
# wspace:左右の余白 、hspace:上下の余白
plt.subplots_adjust(wspace=0.4, hspace=0.6)

plt.show()

グラフの複数配置(オブジェクト指向)

#グラフの複数配置
# 新規のウィンドウを描画
fig = plt.figure(figsize=(10,8)) # Figureオブジェクト作成

# サブプロットを追加
ax1 = fig.add_subplot(2,2,1) # figに属するAxesオブジェクトを左上に作成
ax1.plot(x, y)

ax1.set_xlabel('ax1_X')      #axに軸ラベルを指定するときはset_xlabelを使う
ax1.set_ylabel('ax1_Y')

ax2 = fig.add_subplot(2,2,2) # figに属するAxesオブジェクトを右上に作成
ax2.plot(x*2, y*2)

ax3 = fig.add_subplot(2,2,3) # figに属するAxesオブジェクトを左下に作成
ax3.plot(x*3, y*3)

ax4 = fig.add_subplot(2,2,4) # figに属するAxesオブジェクトを右下に作成
ax4.plot(x*4, y*4)


# グラフ間の間隔を調整
# wspace:左右の余白 、hspace:上下の余白
plt.subplots_adjust(wspace=0.4, hspace=0.6)

plt.show()

等高線

カラーマップ指定のcmapでパターンを指定する。パターンは数十種類用意されている。

サンプルが掲載されている: https://matplotlib.org/examples/color/colormaps_reference.html

'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'hsv', 'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar'

#等高線
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10, 0.05) #x軸の描画範囲の生成。0から10まで0.05刻み。
y = np.arange(0, 10, 0.05) #y軸の描画範囲の生成。0から10まで0.05刻み。

X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.cos(Y)   # 表示する計算式の指定。等高線はZに対して作られる。

plt.figure(figsize=(10,50),dpi=100) #グラフサイズ

# 等高線図の生成
cont=plt.contour(X,Y,Z,  10, vmin=-1,vmax=1, colors=['black'])
cont.clabel(fmt='%1.2f', fontsize=12) #等高線のラベル

# 特定の値で等高線(色指定)を生成
cont1 = plt.contour(X,Y,Z,  levels=[-1.00], colors=['red'], linewidths=3)
cont1.clabel(fmt='%1.2f', fontsize=16) #等高線のラベル

plt.xlabel('X', fontsize=24)
plt.ylabel('Y', fontsize=24)

plt.pcolormesh(X,Y,Z, cmap='rainbow') #カラー等高線図
pp=plt.colorbar (orientation="vertical") # カラーバーの表示 
pp.set_label("Label",  fontsize=24)

plt.show()

さいごに

以上がMatplotlibの基本的な使い方とよく使うであろうコマンドを紹介しました。

Matplotlibにはまだまだいろいろな機能があるので、少しずつマスターしていこうと思いました。

同じくグラフライブラリのSeabornも簡単に綺麗にグラフ化できますが、ちょっとしたグラフだったらMatplotlibでちょちょいっと描いちゃうのが手っ取り早いですね。

-python
-,

Copyright© Program as Life , 2023 All Rights Reserved Powered by AFFINGER5.