Matplotlib による対数軸のプロット作成

MatplotlibMatplotlibBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

このステップバイステップのチュートリアルでは、PythonのMatplotlibを使って対数軸付きのグラフを作成するプロセスを案内します。このチュートリアルでは、以下のトピックを扱います。

  1. 半対数グラフ(Semilogy Plot)
  2. 半対数グラフ(Semilogx Plot)
  3. 対数対数グラフ(Loglog Plot)
  4. 誤差棒グラフ(Errorbars Plot)

VMのヒント

VMの起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebookを使って練習しましょう。

時々、Jupyter Notebookが読み込み終わるまで数秒待つ必要がある場合があります。Jupyter Notebookの制限により、操作の検証を自動化することはできません。

学習中に問題に遭遇した場合は、Labbyにお問い合わせください。セッション後にフィードバックを提供してください。そうすれば、迅速に問題を解決します。

半対数グラフ(Semilogy Plot)

半対数グラフは、y軸に対数スケールを持つグラフです。値の範囲が広いデータを視覚化するのに便利です。

import matplotlib.pyplot as plt
import numpy as np

## Data for plotting
t = np.arange(0.01, 20.0, 0.01)

## Create figure
fig, ax1 = plt.subplots()

## Plot data on semilogy plot
ax1.semilogy(t, np.exp(-t / 5.0))

## Add title and grid to plot
ax1.set(title='半対数グラフ(Semilogy Plot)')
ax1.grid()

## Display plot
plt.show()

半対数グラフ(Semilogx Plot)

半対数グラフは、x軸に対数スケールを持つグラフです。x軸に値の範囲が広いデータを視覚化するのに便利です。

import matplotlib.pyplot as plt
import numpy as np

## Data for plotting
t = np.arange(0.01, 20.0, 0.01)

## Create figure
fig, ax2 = plt.subplots()

## Plot data on semilogx plot
ax2.semilogx(t, np.sin(2 * np.pi * t))

## Add title and grid to plot
ax2.set(title='半対数グラフ(Semilogx Plot)')
ax2.grid()

## Display plot
plt.show()

対数対数グラフ(Loglog Plot)

対数対数グラフは、x軸とy軸の両方に対数スケールを持つグラフです。両軸に値の範囲が広いデータを視覚化するのに便利です。

import matplotlib.pyplot as plt
import numpy as np

## Data for plotting
t = np.arange(0.01, 20.0, 0.01)

## Create figure
fig, ax3 = plt.subplots()

## Plot data on loglog plot
ax3.loglog(t, 20 * np.exp(-t / 10.0))

## Set x-axis scale to base 2
ax3.set_xscale('log', base=2)

## Add title and grid to plot
ax3.set(title='対数対数グラフ(Loglog Plot)')
ax3.grid()

## Display plot
plt.show()

誤差棒グラフ(Errorbars Plot)

誤差棒グラフは、各データポイントに対する誤差棒を表示するグラフです。データポイントが負の値を持つ場合、その値は0.1にクリップされます。

import matplotlib.pyplot as plt
import numpy as np

## Data for plotting
x = 10.0**np.linspace(0.0, 2.0, 20)
y = x**2.0

## Create figure
fig, ax4 = plt.subplots()

## Set x-axis and y-axis to logarithmic scale
ax4.set_xscale("log", nonpositive='clip')
ax4.set_yscale("log", nonpositive='clip')

## Plot data with error bars
ax4.errorbar(x, y, xerr=0.1 * x, yerr=5.0 + 0.75 * y)

## Set title and y-axis limit
ax4.set(title='誤差棒グラフ(Errorbars Plot)')
ax4.set_ylim(bottom=0.1)

## Display plot
plt.show()

まとめ

PythonのMatplotlibは、データ可視化を作成するための強力なツールです。このチュートリアルでは、半対数グラフ(semilogy)、半対数グラフ(semilogx)、対数対数グラフ(loglog)、および誤差棒グラフ(errorbars)を使って対数軸付きのグラフを作成する方法について説明しました。これらの種類のグラフを使用することで、値の範囲が広いデータを効果的に視覚化することができます。