【Python】Matplotlibで作る基本的なグラフの例6個
データの可視化を行う上でPythonのMatplotlibは非常に強力で便利なライブラリで、棒グラフや折れ線グラフ、散布図など、さまざまなグラフを簡単に作成できます。Matplotlibを使って作成できる基本的なグラフの例を6つ紹介します。
目次
棒グラフ (Bar Plot)
import matplotlib.pyplot as plt
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 8, 5]
plt.bar(categories, values, color='skyblue')
plt.title('Bar Plot')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
折れ線グラフ(ポインター有)
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y, marker='o', linestyle='-', color='blue', markerfacecolor='white', markeredgecolor='blue')
plt.title('Line Plot with White Markers')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
折れ線グラフ(ポインター有/領域塗りつぶし)
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y, marker='o', linestyle='-', color='green', markerfacecolor='white', markeredgecolor='green')
plt.fill_between(x, y, color='lightgreen', alpha=0.5)
plt.title('Line Plot with Filled Area')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
散布図 (Scatter Plot)
import matplotlib.pyplot as plt
x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11]
y = [99, 86, 87, 88, 100, 86, 103, 87, 94, 78]
plt.scatter(x, y, color='purple')
plt.title('Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
ヒストグラム (Histogram)
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(1000)
plt.hist(data, bins=20, color='orange', edgecolor='black')
plt.title('Histogram')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
円グラフ (Pie Chart)
import matplotlib.pyplot as plt
sizes = [15, 30, 45, 10]
labels = ['Category A', 'Category B', 'Category C', 'Category D']
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
plt.title('Pie Chart')
plt.axis('equal') # 円を綺麗に見せるための設定
plt.show()
箱ひげ図 (Box Plot)
import matplotlib.pyplot as plt
import numpy as np
# ランダムなデータを生成
np.random.seed(10)
data = [np.random.normal(0, std, 100) for std in range(1, 4)]
# 箱ひげ図の作成
plt.boxplot(data, vert=True, patch_artist=True,
boxprops=dict(facecolor='lightblue', color='blue'),
medianprops=dict(color='red'),
whiskerprops=dict(color='blue'),
capprops=dict(color='blue'))
# タイトルとラベル
plt.title('Box Plot Example')
plt.xticks([1, 2, 3], ['Dataset 1', 'Dataset 2', 'Dataset 3'])
plt.ylabel('Values')
plt.show()
スポンサーリンク






