データポイント付きの Matplotlib 折れ線グラフ

PythonPythonBeginner
オンラインで実践に進む

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

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

はじめに

この実験では、Python の Matplotlib を使ってデータポイント付きの折れ線グラフを作成する方法を学びます。各曲線について、Matplotlib の EventCollection クラスを使って、それぞれの軸上の x と y のデータポイントの位置をマークします。

VM のヒント

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

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

学習中に問題に直面した場合は、Labby にお尋ねください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。

必要なライブラリをインポートする

まず、必要なライブラリをインポートする必要があります。乱数データを作成するために numpy を、グラフを作成するために matplotlib.pyplot を、そしてデータポイントの位置をマークするために matplotlib.collections からの EventCollection を使用します。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import EventCollection

乱数データを作成する

numpy.random.random() 関数を使って、2 つの曲線用の乱数データを作成します。0 から 1 の間の 10 個の乱数の 2 セットを生成し、配列に格納します。

## create random data
xdata = np.random.random([2, 10])

データをソートする

クリーンな曲線を作成するために、sort() メソッドを使ってデータをソートします。

## split the data into two parts
xdata1 = xdata[0, :]
xdata2 = xdata[1, :]
## sort the data so it makes clean curves
xdata1.sort()
xdata2.sort()

y データポイントを作成する

ソートされた x データポイントに対して数学的演算を行うことで、各曲線用のいくつかの y データポイントを作成します。

## create some y data points
ydata1 = xdata1 ** 2
ydata2 = 1 - xdata2 ** 3

グラフを作成する

matplotlib.pyplot.plot() 関数を使ってグラフを作成します。

## plot the data
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(xdata1, ydata1, color='tab:blue')
ax.plot(xdata2, ydata2, color='tab:orange')

イベントを作成する

EventCollection() 関数を使って、x と y のデータポイントを示すイベントを作成します。

## create the events marking the x data points
xevents1 = EventCollection(xdata1, color='tab:blue', linelength=0.05)
xevents2 = EventCollection(xdata2, color='tab:orange', linelength=0.05)

## create the events marking the y data points
yevents1 = EventCollection(ydata1, color='tab:blue', linelength=0.05,
                           orientation='vertical')
yevents2 = EventCollection(ydata2, color='tab:orange', linelength=0.05,
                           orientation='vertical')

グラフにイベントを追加する

matplotlib.pyplot.add_collection() 関数を使って、グラフにイベントを追加します。

## add the events to the axis
ax.add_collection(xevents1)
ax.add_collection(xevents2)
ax.add_collection(yevents1)
ax.add_collection(yevents2)

軸の範囲を設定してタイトルを追加する

matplotlib.pyplot.xlim(), matplotlib.pyplot.ylim(), および matplotlib.pyplot.title() 関数を使って、x 軸と y 軸の範囲を設定し、グラフにタイトルを追加します。

## set the limits
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.set_title('line plot with data points')

グラフを表示する

最後に、matplotlib.pyplot.show() 関数を使ってグラフを表示します。

## display the plot
plt.show()

まとめ

この実験では、Python の Matplotlib を使ってデータポイント付きの折れ線グラフを作成する方法を学びました。Matplotlib の EventCollection クラスを使って、各曲線に対してそれぞれの軸上の x と y のデータポイントの位置を示しました。