LoginSignup
0
2

More than 3 years have passed since last update.

Matplotlib入門

Last updated at Posted at 2021-01-24

Matplotlib入門

Matplotlibはデータの可視化とカスタマイズに最も柔軟性のあるインターフェースpyplotを提供します。
pyplotの簡単な使用方法は以下:

import pandas as pd

df01 = pd.DataFrame(
    {'time': ['1s', '2s', '3s', '4s', '5s'],
     'value': [1, 2, 3, 4, 5]})
df02 = pd.DataFrame(
    {'time': ['1s', '2s', '3s', '4s', '5s'],
     'value': [5, 4, 3, 2, 1]}
)
# matplotlib.pyplotをインポート
import matplotlib.pyplot as plt

# FigureとAxesオブジェクトを作成
fig, ax = plt.subplots()

# df01のvalueをtimeに対してプロット
ax.plot(df01['time'], df01['value'])

# df02のvalueをtimeに対してプロット
ax.plot(df02['time'], df02['value'])

# プロット表示
plt.show()

01.JPG

プロットのカスタマイズ

マーカー、線のスタイル、線の色を設定できます。

また、タイトル、X軸の名称、Y軸の名称も設定できます。

設定可能なフォーマットは matplotlib.pyplot.plot にあります。

# マーカー、線のスタイル、線の色を設定
ax.plot(df01["time"], df01["value"], color='b', marker='o', linestyle='--')
ax.plot(df02["time"], df02["value"], color='r', marker='v', linestyle='--')

# X軸の名称を設定
ax.set_xlabel('Time (s)')

# Y軸の名称を設定
ax.set_ylabel('Value')

# タイトルを設定
ax.set_title('Value patterns in df01 and df02')

plt.show()

02.JPG

サブプロット

プロットにデータを追加しすぎると、場合によってはプロットが煩雑になりすぎて、パターンが見えなくなってしまうことがあります。
その場合はサブプロットを使用します。 matplotlib.pyplot.subplot

# 2行1列のサブプロットを作成
fig, ax = plt.subplots(2, 1)

ax[0].plot(df01['time'], df01['value'])

ax[1].plot(df02['time'], df02['value'])

plt.show()

03.JPG

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