[Python] Matplotlibで2つの折れ線グラフを表示する

Matplotlibで2本の折れ線グラフを作る


今回は、Matplotlibで1つのグラフ上に2つの折れ線グラフを重ねて表示する方法について勉強する。(複数のグラフを作成する方法はこちら

そこで、前回作った2016年の東京の月別平均気温の折れ線グラスフを使い、そこに沖縄の月別平均気温の折れ線グラフを追加することにする。

前回作った2016年の東京の月別平均気温を表示するコードは以下の通り。

import matplotlib.pyplot as plt

x_datas = range(1, 13)
y_datas =  [6.1, 7.2, 10.1, 15.4, 20.2, 22.4, 25.4, 27.1, 24.4, 18.7, 11.4, 8.9]

months = ['Jan', 'Feb', 'Mar', 'Apr', 
    'May', 'Jun','Jul', 'Aug', 
    'Sep', 'Oct', 'Nov', 'Dec']

plt.plot(x_datas, y_datas, marker = 'o')
plt.xticks(x_datas, months)
plt.xlim(0, 13)
plt.ylim(0, 30)

#フォントサイズをまとめて変更する場合
#plt.rcParams["font.size"] = 18

plt.title('The average temperature in Tokyo(2016)', fontsize = 20)
plt.xlabel('month', fontsize = 16)
plt.ylabel('temperature', fontsize = 16)
plt.tick_params(labelsize=14)
plt.grid(True)
plt.show()

グラフ1
前回作ったグラフ



2本の折れ線グラフを表示する

表示する折れ線グラフを増やすのは、単純にplt.plot(x軸, y軸)を追加するだけでいい。

まず、前回のコードを少し変更し、東京の平均気温気温を入れているy_datasというリストをtokyoという名前にする。また、沖縄の平均気温が高いのでy軸の最大値を変更する。
ついでにグラフのタイトルからTokyoを取り除く。

次にokinawaというリストに沖縄の平均気温を入力し、グラフを作成することにする。

import matplotlib.pyplot as plt

x_datas = range(1, 13)
tokyo =  [6.1, 7.2, 10.1, 15.4, 20.2, 22.4, 25.4, 27.1, 24.4, 18.7, 11.4, 8.9]

#沖縄の平均気温を追加
okinawa = [17.4, 16.9, 18.7, 23.0, 25.7, 28.4, 29.8, 29.5, 28.4, 27.7, 23.2, 20.5]

months = ['Jan', 'Feb', 'Mar', 'Apr', 
    'May', 'Jun','Jul', 'Aug', 
    'Sep', 'Oct', 'Nov', 'Dec']

plt.plot(x_datas, tokyo, marker = 'o')
plt.plot(x_datas, okinawa, marker = 'x')

plt.xticks(x_datas, months)
plt.xlim(0, 13)
plt.ylim(0, 35) #y軸の最大値を変更30→35

plt.title('The average temperature in 2016', fontsize = 20)
plt.xlabel('month', fontsize = 16)
plt.ylabel('temperature', fontsize = 16)
plt.tick_params(labelsize=14)
plt.grid(True)
plt.show()

沖縄のグラフのmarkerには'x'を指定した。

出来上がったのが下のグラフ。
グラフ2


これで、いちおう2系列の折れ線グラフを作成することができた。しかし、ぱっと見でどっちのグラフがどっちの系列を表しているのかがわからない。

そこで、どのグラフが何を表しているのかが分かるようにするために、グラフに凡例を表示することにする。

グラフに凡例を表示する

凡例を表示するためには2つの手順が必要になる。

  1. plt.plot()の引数labelに表示する凡例を指定する。
  2. plt.legend()で凡例を表示する位置を指定する。

今回は、引数loc'upper right'を指定し、凡例を右上に表示する。

import matplotlib.pyplot as plt

x_datas = range(1, 13)
tokyo =  [6.1, 7.2, 10.1, 15.4, 20.2, 22.4, 25.4, 27.1, 24.4, 18.7, 11.4, 8.9]

#沖縄の平均気温を追加
okinawa = [17.4, 16.9, 18.7, 23.0, 25.7, 28.4, 29.8, 29.5, 28.4, 27.7, 23.2, 20.5]

months = ['Jan', 'Feb', 'Mar', 'Apr', 
    'May', 'Jun','Jul', 'Aug', 
    'Sep', 'Oct', 'Nov', 'Dec']

plt.plot(x_datas, tokyo, marker = 'o', label = 'Tokyo')
plt.plot(x_datas, okinawa, marker = 'x', label = 'Okinawa')

plt.xticks(x_datas, months)
plt.xlim(0, 13)
plt.ylim(0, 35) #y軸の最大値を変更30→35

plt.title('The average temperature in 2016', fontsize = 20)
plt.xlabel('month', fontsize = 16)
plt.ylabel('temperature', fontsize = 16)
plt.tick_params(labelsize=14)
plt.grid(True)
plt.legend(loc = 'upper right')
plt.show()

グラフ3

これで、1つのグラフ上に2つの折れ線を表示することができた。



以上、Matplotlibで2本の折れ線グラフを表示する方法について。

今回は、ここまで

少しずつだけど、色々できるようになるのは楽しい


0 件のコメント :