Pythonとmatplotlibを使って、さまざまな種類のグラフを作成する方法を紹介します。ここでは、折れ線グラフ、散布図、棒グラフ、ヒストグラムの作成方法について説明します。
折れ線グラフ
折れ線グラフは、plt.plot()
関数を使用して作成します。以下に一例を示します。
from matplotlib import pyplot as plt
from random import randint
# データの定義(サンプルなのでテキトー)
x = list(range(10))
y = [randint(0, 100) for _ in x]
# グラフの描画
plt.plot(x, y)
plt.show()
散布図
散布図は、plt.scatter()
関数を使用して作成します。以下に一例を示します。
from matplotlib import pyplot as plt
from random import randint
# データの定義(サンプルなのでテキトー)
x = list(range(10))
y = [randint(0, 100) for _ in x]
# グラフの描画
plt.scatter(x, y)
plt.show()
棒グラフ
棒グラフは、plt.bar()
関数を使用して作成します。以下に一例を示します。
from matplotlib import pyplot as plt
from random import randint
# データの定義(サンプルなのでテキトー)
x = list(range(10))
y = [randint(0, 100) for _ in x]
# グラフの描画
plt.bar(x, y)
plt.show()
ヒストグラム
ヒストグラムは、plt.hist()
関数を使用して作成します。以下に一例を示します。
from matplotlib import pyplot as plt
from random import randint
# データの定義(サンプルなのでテキトー)
y = [randint(0, 100) for _ in range(1000)]
# グラフの描画
plt.hist(y, 30)
plt.show()
以上、Pythonとmatplotlibを使った基本的なグラフ作成方法について説明しました。これらの基本的な方法を理解すれば、さまざまなデータを視覚化することが可能になります。.