Matplotlib のマジック関数インライン

Salman Mehmood 2024年2月15日
Matplotlib のマジック関数インライン

このデモンストレーションでは、マジック関数とは何かを学び、Matplotlib で利用できるさまざまなマジック関数を確認します。 この後、インライン関数について説明します。

Matplotlib でインライン マジック関数を使用する

Interactive Python には、マジック関数と呼ばれる定義済みの関数がいくつか用意されており、これらのマジック関数は、コマンドラインおよびスタイル構文によって呼び出し可能に使用できます。 ライン指向セル指向 という 2 種類のマジック関数があります。

行指向 は行マジックとも呼ばれ、これらの関数は % 記号で始まり、引用符や括弧なしで行の残りの部分に引数が続きます。 インタラクティブな Python を使用している場合は、jupyter ノートブックを意味する "ipython" セッションとも言えます。

以下は、関数を呼び出すための構文です。

%matplotlib [gui]

ここで、[gui] は、関数を呼び出して有効にする Matplotlib バックエンドの名前です。 利用可能な Matplotlib パッケージのリストを表示するには、次のコマンドを使用する必要があります。

指図:

%matplotlib -l

出力:

Available matplotlib backends: ['tk', 'gtk', 'gtk3', 'gtk4', 'wx', 'qt4', 'qt5', 'qt6', 'qt', 'osx', 'nbagg', 'notebook', 'agg', 'svg', 'pdf', 'ps', 'inline', 'ipympl', 'widget']

以下のコマンドは、それを確認する別の方法であり、上記と同じ結果が表示されます。

%matplotlib --list

ここで、プロットとグラフがセルのすぐ下に表示されるインライン プロットを有効にする魔法の関数 %matplotlib inline について説明します。 前のプロットには影響しないカラーマップを使用してプロットの色を変更したいとします。

このインライン関数を jupyter ノートブックで使用する方法を学びましょう。その例を次に示します。 プログラムを実行すると、ここにプロットが表示され、どのように見えるかがわかります。

コード:

from matplotlib import pyplot as plt

# %matplotlib inline

x1 = [1, 5, 8, 11, 14, 11]
y1 = [12, 11, 15, 1, 22, 15]
y2 = [10, 12, 15, 10, 20, 10]
y3 = [11, 9, 15, 10, 12, 14]

plt.figure(figsize=[9, 7])

plt.title("%matplotlib inline")
plt.plot(x1, y1, linewidth=2, label="sin()")
plt.plot(x1, y2, linewidth=2, label="cos()")
plt.plot(x1, y3, linewidth=2, label="tan()")

出力:

jupyter Notebook の matplotlib インライン関数

現在のバージョンの ipython ノートブックと jupyter ノートブックを使用している場合は、インライン関数を使用する必要はありません。 Matplotlib の show() 関数を呼び出すかどうかに関係なく、いずれの場合もグラフ出力が表示されます。

コード:

from matplotlib import pyplot as plt

x1 = [1, 5, 8, 11, 14, 11]
y1 = [12, 11, 15, 1, 22, 15]
y2 = [10, 12, 15, 10, 20, 10]
y3 = [11, 9, 15, 10, 12, 14]

plt.figure(figsize=[9, 7])

plt.title("%matplotlib inline")
plt.plot(x1, y1, linewidth=2, label="sin()")
plt.plot(x1, y2, linewidth=2, label="cos()")
plt.plot(x1, y3, linewidth=2, label="tan()")

この Matplotlib を pycharm でインラインで使用しようとすると、構文エラーが表示されますが、Visual Studio で使用する場合は、拡張機能 "jupyter note" を追加する必要があります。

著者: Salman Mehmood
Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn