KMDのプログラミングメモノート

主にUnity(C#)を中心としたプログラムの備忘録

Python matplotlibを利用したグラフ描画の基本





折れ線グラフの描画

import matplotlib.pyplot as plt

#xとyの定義
x = [0, 1, 2, 3] 
y = [1, -3, 4, 2]

#グラフの描画
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)

#グラフの表示
plt.show()


実行結果





軸ラベルとタイトルの表示

概要

軸ラベルを表示するには、

ax.set_xlabel('横軸の名前')
ax.set_ylabel('縦軸の名前')

とすれば軸ラベルを表示することができ、

ax.set_title('グラフのタイトル')

とすればグラフのタイトルを表示することができます。


使用例

import matplotlib.pyplot as plt

#xとyの定義
x = [0, 1, 2, 3] 
y = [1, -3, 4, 2]

#グラフの描画
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)

#軸ラベルの追加
ax.set_xlabel('x')
ax.set_ylabel('y')

#タイトルの追加
ax.set_title('Sample Title')

#グラフの表示
plt.show()


実行結果





日本語での軸ラベルとタイトルの表示

概要

軸ラベルやタイトルを日本語でするには

plt.rcParams['font.family'] = 'MS Gothic'

とする必要があります。


使用例

import matplotlib.pyplot as plt

#xとyの定義
x = [0, 1, 2, 3] 
y = [1, -3, 4, 2]

# 軸ラベルなどを日本語表記できるようにfontを変更
plt.rcParams['font.family'] = 'MS Gothic'

#グラフの描画
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)

#軸ラベルの追加
ax.set_xlabel('横軸')
ax.set_ylabel('縦軸')

#タイトルの追加
ax.set_title('日本語タイトル')

#グラフの表示
plt.show()


実行結果





散布図の表示

概要

ax.scatter(x, y)

とすることで散布図が表示できます。


使用例

import matplotlib.pyplot as plt

#xとyの定義
x = [0, 1, 2, 3] 
y = [1, -3, 4, 2]

#グラフの描画
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y)

#グラフの表示
plt.show()


実行結果





棒グラフの表示

概要

ax.bar(x, y)

とすることで散布図が表示できます。


使用例

import matplotlib.pyplot as plt

#xとyの定義
x = [0, 1, 2, 3] 
y = [1, -3, 4, 2]

#グラフの描画
fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x, y)

#グラフの表示
plt.show()


実行結果





水平線や垂直線の描画

概要

ax.axhline(a)

とすることでグラフのy=aの位置に水平線を、

ax.axvline(a)

とすることでグラフのx=aの位置に水直線を描画できる


使用例

import matplotlib.pyplot as plt

#xとyの定義
x = [0, 1, 2, 3] 
y = [1, -3, 4, 2]

#グラフの描画
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)

#y=2に赤い線の追加
ax.axhline(2, color="#ff0000")

#x=2に黒い線の追加
ax.axvline(0, color="#000000")

#グラフの表示
plt.show()


実行結果