導入
折れ線グラフは、時間による変化や推移を見るのが得意です。売上の月次推移、気温の変化などに使います。
説明
plt.plot(x, y) で、横軸 x・縦軸 y の折れ線を描きます。x を省くと 0,1,2… が自動で使われます。
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5, 6]
sales = [120, 150, 90, 200, 170, 220]
plt.plot(months, sales, marker="o")
plt.title("Monthly Sales")
plt.xlabel("month")
plt.ylabel("sales")
plt.grid(True)
plt.show()
marker="o" で各点に丸印、plt.grid(True) で補助線が入り、値が読み取りやすくなります。
2本以上の線を重ねて比較することもできます。label と plt.legend() で凡例を付けます。
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
tokyo = [22, 25, 19, 30, 28]
osaka = [24, 27, 21, 31, 29]
plt.plot(x, tokyo, marker="o", label="Tokyo")
plt.plot(x, osaka, marker="s", label="Osaka")
plt.title("Temperature")
plt.legend()
plt.show()
やってみよう
plt.plot の色を plt.plot(months, sales, color="red") のように変えてみましょう。linestyle="--" で破線にもできます。
演習
[10, 40, 30, 60, 50] を折れ線グラフにして、タイトルを "trend" として表示してください。
ヒント1を見る
plt.plot([10,40,30,60,50]) → plt.title("trend") → plt.show()。