0
4

今すぐ試せる!Pythonのデータ可視化ライブラリMatplotlibで作れるチャートまとめ

Last updated at Posted at 2024-08-12

はじめに

Matplotlibは、Pythonで最も広く使われているデータ可視化ライブラリの一つです。

その豊富な機能と柔軟性により、科学技術計算からビジネス分析まで幅広い分野で活用されています。

本記事では、Matplotlibの主要なグラフ種類を紹介し、それぞれのコード例を交えながら解説していきます。

1. 折れ線グラフ

折れ線グラフは、時系列データの表現に適しています。以下のコードで簡単に作成できます。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title('正弦波')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.show()

2. 棒グラフ

カテゴリ別の比較に適した棒グラフは、以下のように作成します。

categories = ['A', 'B', 'C', 'D']
values = [4, 7, 2, 8]
plt.bar(categories, values)
plt.title('カテゴリ別の値')
plt.show()

3. 散布図

2つの変数間の関係を視覚化するのに適した散布図は、次のコードで作成できます。

x = np.random.rand(50)
y = np.random.rand(50)
plt.scatter(x, y)
plt.title('ランダムな散布図')
plt.show()

4. ヒストグラム

データの分布を表現するヒストグラムは、以下のように作成します。

data = np.random.randn(1000)
plt.hist(data, bins=30)
plt.title('正規分布のヒストグラム')
plt.show()

5. 円グラフ

全体に対する部分の割合を示す円グラフは、次のコードで作成できます。

sizes = [35, 25, 20, 15, 5]
labels = ['A', 'B', 'C', 'D', 'E']
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('円グラフの例')
plt.show()

6. 箱ひげ図

データの分布や外れ値を視覚化する箱ひげ図は、以下のように作成します。

data = [np.random.normal(0, std, 100) for std in range(1, 4)]
plt.boxplot(data)
plt.title('箱ひげ図の例')
plt.show()

7. ヒートマップ

2次元データの値を色で表現するヒートマップは、次のコードで作成できます。

data = np.random.rand(10, 10)
plt.imshow(data, cmap='hot')
plt.colorbar()
plt.title('ヒートマップの例')
plt.show()

8. 3Dプロット

3次元データを表現する3Dプロットは、以下のように作成します。

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
ax.scatter(x, y, z)
plt.title('3D散布図')
plt.show()

9. 極座標プロット

極座標系でデータを表現する極座標プロットは、次のコードで作成できます。

r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r)
plt.title('極座標プロット')
plt.show()

10. サブプロット

複数のグラフを1つの図に配置するサブプロットは、以下のように作成します。

fig, axs = plt.subplots(2, 2, figsize=(10, 10))
axs[0, 0].plot(np.random.rand(100))
axs[0, 1].scatter(np.random.rand(100), np.random.rand(100))
axs[1, 0].hist(np.random.randn(1000), bins=30)
axs[1, 1].imshow(np.random.rand(10, 10), cmap='viridis')
plt.tight_layout()
plt.show()

11. エラーバー付きグラフ

実験データなどを表現する際に重要なエラーバー付きグラフは、以下のように作成できます。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 50)
y = np.sin(x)
yerr = np.random.rand(50) * 0.1

plt.errorbar(x, y, yerr=yerr, fmt='o', capsize=5)
plt.title('エラーバー付きグラフ')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.show()

12. 積み上げ棒グラフ

複数のカテゴリーの合計と内訳を同時に表現できる積み上げ棒グラフは、次のコードで作成します。

categories = ['A', 'B', 'C', 'D']
men_means = [20, 35, 30, 35]
women_means = [25, 32, 34, 20]

width = 0.35
fig, ax = plt.subplots()

ax.bar(categories, men_means, width, label='Men')
ax.bar(categories, women_means, width, bottom=men_means, label='Women')

ax.set_ylabel('Scores')
ax.set_title('積み上げ棒グラフ')
ax.legend()

plt.show()

13. バイオリンプロット

箱ひげ図の拡張版とも言えるバイオリンプロットは、データの分布をより詳細に表現します。

import seaborn as sns

# Seabornを使用してバイオリンプロットを作成
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
plt.figure(figsize=(10, 6))
sns.violinplot(x="day", y="total_bill", data=tips)
plt.title('バイオリンプロット')
plt.show()

14. 等高線プロット

3次元データを2次元平面上に表現する等高線プロットは、以下のように作成できます。

def f(x, y):
    return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)

plt.contourf(X, Y, Z, 20, cmap='RdGy')
plt.colorbar()
plt.title('等高線プロット')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

15. アニメーションプロット

データの時間変化を表現するアニメーションプロットは、次のように作成します。

from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.title('アニメーションプロット')
plt.show()

まとめ

Matplotlibは非常に強力で柔軟なデータ可視化ツールです。

本記事で紹介した15種類のグラフは、その機能のほんの一部に過ぎません。

実際のデータ分析や研究において、これらのグラフを組み合わせたり、カスタマイズしたりすることで、より効果的なデータの可視化が可能となります。

Matplotlibの公式ドキュメントを参照しながら、さらに高度な使い方を学んでいくことをおすすめします。

0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4