matplotlib vs seaborn:データ可視化ライブラリ徹底比較!

Python
この記事は約12分で読めます。

こんにちは、JS2IIUです。

Pythonでデータ可視化を行う際、matplotlibseabornはどちらも強力なライブラリとして知られています。

matplotlibはPythonのデータ可視化ライブラリの基礎とも言える存在で、非常に柔軟性が高く、様々な種類のグラフを作成できます。一方、seabornmatplotlibをベースに構築されており、より統計的なデータ可視化に特化し、美しいグラフを簡単に作成できるのが特徴です。

本記事では、matplotlibseabornの共通点と相違点を整理し、具体的なプロット事例を通してそれぞれの特徴を解説していきます。特に、統計的な解析に役立つプロットを中心に、両ライブラリの違いを深く理解できるように説明していきます。今回も、よろしくお願いします。

matplotlibとseabornの特徴一覧

特徴matplotlibseaborn
目的汎用的な可視化統計的可視化
ベースmatplotlib
使いやすさ自由度が高い分、コードはやや複雑になりがちシンプルなコードで美しいグラフを作成可能
見た目の美しさデフォルトではシンプルデフォルトで洗練されたデザイン
データの扱いNumPy配列やリストに最適Pandas DataFrameとの相性が良い
複雑なプロット手動で設定が必要複雑な統計プロットも関数で簡単に作成可能
カスタマイズ性高いある程度可能
拡張性高いmatplotlibの拡張機能を利用可能

プロット事例で比較!

それでは、具体的なプロット事例を通して、matplotlibseabornの違いを見ていきましょう。今回は、サンプルデータとしてirisデータセットとtipsデータセットを使用します。

散布図

matplotlib:

Python
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

iris = load_iris()
X = iris.data[:, :2]  # sepal length and sepal width
y = iris.target

plt.figure(figsize=(8, 6))
plt.scatter(X[y == 0, 0], X[y == 0, 1], label='setosa')
plt.scatter(X[y == 1, 0], X[y == 1, 1], label='versicolor')
plt.scatter(X[y == 2, 0], X[y == 2, 1], label='virginica')

plt.xlabel('Sepal length (cm)')
plt.ylabel('Sepal width (cm)')
plt.title('Scatter plot with matplotlib')
plt.legend()
plt.show()

seaborn:

Python
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

iris = load_iris()
df = sns.load_dataset('iris')

plt.figure(figsize=(8, 6))
sns.scatterplot(x='sepal_length', y='sepal_width', hue='species', data=df)

plt.xlabel('Sepal length (cm)')
plt.ylabel('Sepal width (cm)')
plt.title('Scatter plot with seaborn')
plt.show()

seabornでは、hue引数で簡単に色分けができ、凡例も自動で追加されます。matplotlibでは、これらの設定を手動で行う必要があります。

ヒストグラム

matplotlib:

Python
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

iris = load_iris()
X = iris.data[:, 0]  # sepal length

plt.figure(figsize=(8, 6))
plt.hist(X, bins=10)

plt.xlabel('Sepal length (cm)')
plt.ylabel('Frequency')
plt.title('Histogram with matplotlib')
plt.show()

seaborn:

Python
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

iris = load_iris()
df = sns.load_dataset('iris')

plt.figure(figsize=(8, 6))
sns.histplot(x='sepal_length', data=df)

plt.xlabel('Sepal length (cm)')
plt.ylabel('Frequency')
plt.title('Histogram with seaborn')
plt.show()

seabornでは、kde引数を指定することで、カーネル密度推定による曲線を重ねて表示することもできます。

箱ひげ図

matplotlib:

Python
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

iris = load_iris()
data = [iris.data[iris.target == i, 0] for i in range(3)]

plt.figure(figsize=(8, 6))
plt.boxplot(data, labels=iris.target_names)

plt.xlabel('Species')
plt.ylabel('Sepal length (cm)')
plt.title('Box plot with matplotlib')
plt.show()

seaborn:

Python
import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')

plt.figure(figsize=(8, 6))
sns.boxplot(x='species', y='sepal_length', data=df)

plt.xlabel('Species')
plt.ylabel('Sepal length (cm)')
plt.title('Box plot with seaborn')
plt.show()

seabornでは、xy引数にカラム名を指定するだけで簡単に箱ひげ図を作成できます。

バイオリンプロット

matplotlib:

matplotlibでは、バイオリンプロットを直接作成する関数がありません。そのため、violinplot関数を実装するか、他のライブラリを利用する必要があります。

seaborn:

Python
import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')

plt.figure(figsize=(8, 6))
sns.violinplot(x='species', y='sepal_length', data=df)

plt.xlabel('Species')
plt.ylabel('Sepal length (cm)')
plt.title('Violin plot with seaborn')
plt.show()

seabornでは、violinplot関数で簡単にバイオリンプロットを作成できます。バイオリンプロットは、箱ひげ図とカーネル密度推定を組み合わせたもので、データの分布をより詳細に把握できます。

ヒートマップ

matplotlib:

Python
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

df = sns.load_dataset('iris')
corr = df.drop('species', axis=1).corr() 

plt.figure(figsize=(8, 6))
plt.imshow(corr, cmap='coolwarm', interpolation='nearest')
plt.colorbar()
plt.xticks(range(len(corr)), corr.columns, rotation=45)
plt.yticks(range(len(corr)), corr.columns)
plt.title('Heatmap with matplotlib')
plt.show()

seaborn:

Python
import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')
corr = df.drop('species', axis=1).corr() 

plt.figure(figsize=(8, 6))
sns.heatmap(corr, annot=True, cmap='coolwarm')
plt.title('Heatmap with seaborn')
plt.show()

seabornでは、heatmap関数で簡単にヒートマップを作成できます。annot=Trueを指定することで、各セルに値を表示することもできます。

ペアプロット

matplotlib:

matplotlibでは、ペアプロットを直接作成する関数がありません。そのため、scatter関数などを用いて、複数の散布図を組み合わせる必要があります。

seaborn:

Python
import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')

sns.pairplot(df, hue='species')
plt.title('Pairplot with seaborn')
plt.show()

seabornでは、pairplot関数で簡単にペアプロットを作成できます。ペアプロットは、データセット内の全ての変数のペアに対して散布図を作成し、変数間の関係を一覧で確認できます。

ジョイントプロット

matplotlib:

matplotlibでは、ジョイントプロットを直接作成する関数がありません。そのため、scatter関数とhist関数を組み合わせて作成する必要があります。

seaborn:

Python
import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')

sns.jointplot(x='sepal_length', y='sepal_width', data=df, kind='kde')
plt.title('Jointplot with seaborn')
plt.show()

seabornでは、jointplot関数で簡単にジョイントプロットを作成できます。ジョイントプロットは、2つの変数の散布図とそれぞれのヒストグラムを組み合わせて表示するもので、変数間の関係とそれぞれの分布を同時に確認できます。kind引数で表示するグラフの種類を指定できます。

まとめ

matplotlibは柔軟性が高く、細かいカスタマイズが可能な一方、seabornは統計的な可視化に特化し、美しいグラフを簡単に作成できます。どちらのライブラリもPythonでのデータ可視化において重要な役割を果たしており、目的に合わせて使い分けることが重要です。

seabornのメリット:

  • 美しいグラフを簡単に作成できる
  • 統計的な可視化に特化した関数が多い
  • Pandas DataFrameとの連携がスムーズ

matplotlibのメリット:

  • 柔軟性が高く、細かいカスタマイズが可能
  • 非常に多くの種類のグラフを作成できる
  • 他のライブラリとの連携性が高い

本記事が、matplotlibseabornの理解を深める一助となれば幸いです。

Pythonに関する書籍の<PR>です。

24年9月に出版された「ハイパーモダンPython-信頼性の高いワークフローを構築するモダンテクニック」、Claudio Jolowicz著、嶋田、鈴木訳。開発環境の構築、プロジェクトの管理、テストに関して実践的な内容でとても参考になる一冊です。

最後まで読んでいただきありがとうございました。

コメント

タイトルとURLをコピーしました