LoginSignup
0
1

More than 1 year has passed since last update.

Matplotlib入門【データ分析ライブラリ三種の神器③】

Last updated at Posted at 2023-05-07

はじめに

データ分析ライブラリ三種の神器である「Numpy」「Pandas」「Matplotlib」についての入門記事です。ソースコードはこちら

Numpy入門【データ分析ライブラリ三種の神器①】
Pandas入門【データ分析ライブラリ三種の神器②】
Matplotlib入門【データ分析ライブラリ三種の神器③】

Matplotlibは、Pythonのデータ可視化ライブラリであり、グラフやチャートを描画するために広く使われています。この記事では、Matplotlibの基本的な使い方を紹介します。

1. インストールとインポート

まずは、Matplotlibをインストールします。以下のコマンドを実行してください。

pip install matplotlib

次に、Matplotlibのpyplotモジュールをインポートします。慣習的にpltという名前でインポートされます。

import matplotlib.pyplot as plt

2. 基本的なグラフの描画

2.1 折れ線グラフ

import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.show()

2.2 散布図

x = np.random.rand(50)
y = np.random.rand(50)

plt.scatter(x, y)
plt.show()

2.3 ヒストグラム

data = np.random.randn(1000)

plt.hist(data, bins=30)
plt.show()

3. グラフのカスタマイズ

3.1 タイトルと軸ラベル

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show()

3.2 グリッドの表示

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.grid()
plt.show()

3.3 凡例の追加

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')
plt.legend()
plt.show()

4. 複数のグラフを描画する

4.1 サブプロット

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

fig, axes = plt.subplots(nrows=2, ncols=1)

axes[0].plot(x, y1)
axes[0].set_title('sin(x)')

axes[1].plot(x, y2)
axes[1].set_title('cos(x)')

plt.tight_layout()
plt.show()

これで、Matplotlibの基本的な使い方を一通り紹介しました。実際のデータ解析では、これらの機能を組み合わせてデータを可視化します。Matplotlibは非常に柔軟で強力なライブラリであるため、ぜひ活用してみてください。

Numpy入門【データ分析ライブラリ三種の神器①】
Pandas入門【データ分析ライブラリ三種の神器②】
Matplotlib入門【データ分析ライブラリ三種の神器③】

0
1
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
1