Python入門トップページ


目次

  1. Matplotlib とは
  2. モジュールの読み込み
  3. 折れ線グラフ
  4. 散布図
  5. 円グラフ
  6. 棒グラフ
  7. 複数の棒グラフ
  8. 積み上げグラフ
  9. 任意の数学関数のグラフ描画
  10. 複数グラフの描画

Matplotlib によるグラフの描画

折れ線グラフ

ある都市のある日の気温データについて折れ線グラフを作成してみよう.まずはここ参考にモジュールを読み込んだ後,データフレームを準備する.

データフレームを準備するimport matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame([
    [0, 12.7], [1, 12.4], [2, 11.8], [3, 12.2],
    [4, 11.4], [5, 11.5], [6, 10.8], [7, 11.5],
    [8, 12.3], [9, 13.6], [10, 13.8], [11, 13.8],
    [12, 13.6], [13, 12.5], [14, 12.6], [15, 13.0],
    [16, 13.7], [17, 13.4], [18, 12.3], [19, 11.7],
    [20, 11.1], [21, 10.7], [22, 10.4], [23, 10.2]],
    columns=['hour', 'temperature']
)
print(df.head())
   hour  temperature
0     0         12.7
1     1         12.4
2     2         11.8
3     3         12.2
4     4         11.4

目次に戻る

グラフを描画するには,figure オブジェクトと subplots を生成する必要がある.figure オブジェクトは(いくつかの,ただし以下では1つの)subplots を描画する領域で,subplots はグラフを描画する領域である.次のコードのように,plt.subplots() 関数によって,figure オブジェクトと subplots の配置を一気に行うことができる.その後,plot() 関数で折れ線グラフを描画することができる.

折れ線グラフfig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'])
plt.show()
mpl-1-01

目次に戻る

マーカーを表示するには marker オプションを指定する.

マーカーを表示するfig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o')
plt.show()
mpl-1-02

目次に戻る

軸ラベルを表示してみよう.

軸ラベルを表示するfig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
plt.show()
mpl-1-03

目次に戻る

縦軸,横軸の範囲を指定してみよう.

軸の範囲を設定するfig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(5, 20)
plt.show()
mpl-1-04

目次に戻る

凡例を表示してみよう.なお,凡例の位置を変更するためには,ax.legend()loc 引数を指定して,ax.legend(loc='upper right') のようにするとよい.ここで,loc には,'best''upper right''upper left''lower right''lower left''center left''center right''lower center''upper center''center' などが利用できます.詳細は https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html を参照してください.

凡例を追加するfig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o', label='temparature')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(5, 20)
ax.legend()
plt.show()
mpl-1-05

目次に戻る

グリッドを表示する.

グリッドを表示するfig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o', label='temparature')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(5, 20)
ax.legend()
ax.grid()
plt.show()
mpl-1-06

目次に戻る

横軸の刻み幅を変更してみよう.

横軸の刻みを変更するfig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o', label='temparature')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(5, 20)
ax.legend()
ax.grid()
ax.set_xticks(np.arange(0, 23 + 1, 6))
plt.show()
mpl-1-07

目次に戻る

グラフにタイトルを表示するには,title() を実行すると良い.

タイトルの表示fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o', label='temparature')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(5, 20)
ax.legend()
ax.grid()
ax.set_xticks(np.arange(0, 23 + 1, 6))
ax.set_title('temperature')
plt.show()
mpl-1-08

目次に戻る

なおタイトル等に日本語文字を入力しただけではフォントの設定の問題で正しく表示できない.

日本語タイトルの表示:失敗例fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o', label='temparature')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(5, 20)
ax.legend()
ax.grid()
ax.set_xticks(np.arange(0, 23 + 1, 6))
ax.set_title('気温')
plt.show()
mpl-1-09

日本語フォントを利用するためには matplotlib.font_manager インポートし,任意のフォントへのパスを指定すると良い.このときフォントパスは各自の環境に合わせてください.

日本語タイトルの表示import matplotlib.font_manager as fm

f_prop = fm.FontProperties(fname="C:\\Windows\\Fonts\\meiryo.ttc") # Windows の場合
# f_prop = fm.FontProperties(fname="/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc") # Mac の場合はこの行を有効に
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o', label='temparature')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(5, 20)
ax.legend()
ax.grid()
ax.set_xticks(np.arange(0, 23 + 1, 6))
ax.set_title('気温', fontproperties=f_prop)
plt.show()
mpl-1-10

目次に戻る

なお,グラフを画像形式でファイルに保存には,plt.show() の代わりに plt.savefig('ファイル名.png') を実行すると良い.このとき,ノートブックと同じフォルダに PNG 形式で保存される.

PNG 形式で保存するfig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o', label='temparature')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(5, 20)
ax.legend()
ax.grid()
ax.set_xticks(np.arange(0, 23 + 1, 6))
ax.set_title('temperature')
plt.savefig('fig.png')

上で生成されたラスター形式の PNG ファイルでは作成された画像の解像度が若干粗く,塗りつぶし色が透明になっている.解像度は dpi オプションで,塗りつぶし色は facecolor オプションで変更することができる.

PNG ファイルの解像度と塗りつぶし色の指定fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o', label='temparature')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(5, 20)
ax.legend()
ax.grid()
ax.set_xticks(np.arange(0, 23 + 1, 6))
ax.set_title('temperature')
plt.savefig('fig.png', dpi=300, facecolor='white')

さらに,PDF 形式(あるいは EPS 形式)で保存することも可能である.ベクター形式の PDF ファイルではグラフの要素や文字もアウトライン化されているため,拡大表示しても美しい状態を保つことができる.

PDF 形式で保存するfig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df['hour'], df['temperature'], marker='o', label='temparature')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(5, 20)
ax.legend()
ax.grid()
ax.set_xticks(np.arange(0, 23 + 1, 6))
ax.set_title('temperature')
plt.savefig('fig.pdf')

目次に戻る

次に,複数の折れ線を一つのグラフに表示してみよう.まず,ある日の2つの地点(地点Aと地点B)の気温データをデータフレームで準備します.

データフレームの準備df2 = pd.DataFrame([
    [0, 19.1, 15.9], [1, 17.4, 15.5], [2, 17, 15],
    [3, 16.4, 14.4], [4, 16.2, 13.8], [5, 15.5, 12.8],
    [6, 16.4, 13.3], [7, 17.6, 15.2], [8, 20, 17.7],
    [9, 20.8, 19.8], [10, 22.6, 21.8], [11, 22.7, 23.2],
    [12, 25.3, 23.6], [13, 24.3, 23.9], [14, 24.5, 24.1],
    [15, 23.9, 23.5], [16, 23.5, 23.3], [17, 22.6, 21.3],
    [18, 21.6, 19.6], [19, 19.8, 17.9], [20, 19.4, 16.3],
    [21, 18.8, 15.2], [22, 17.9, 14.2], [23, 17.9, 13.8]],
    columns=['hour', 'A', 'B']
)
print(df2.head())
   hour     A     B
0     0  19.1  15.9
1     1  17.4  15.5
2     2  17.0  15.0
3     3  16.4  14.4
4     4  16.2  13.8

複数の折れ線を表示するには,次のように ax.plot を続けて実行すると良いでしょう.なお,marker には 'o''x''+' など様々な種類が準備されています.詳細はこちらで確認して下さい.

fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(df2['hour'], df2['A'], marker='o', label='A')
ax.plot(df2['hour'], df2['B'], marker='x', label='B')
ax.set_xlabel('hour')
ax.set_ylabel('temperature')
ax.set_xlim(0, 23)
ax.set_ylim(10, 30)
ax.legend()
ax.grid()
ax.set_xticks(np.arange(0, 23 + 1, 6))
plt.show()
mpl-1-13

目次に戻る