Matplotlib ツールと対話関数


Matplotlib 参考文档Matplotlib リファレンスドキュメント

これらの関数は、イベント処理、属性操作、マウス操作、デバッグツールを提供します。

関数一覧

関数機能
connect()イベントコールバック関数をバインド
disconnect()イベントコールバック関数のバインドを解除
ginput()マウスクリックで座標を取得
waitforbuttonpress()マウスまたはキーボードの入力を待機
findobj()条件に一致する Artist を検索
get() / setp()Artist 属性の取得/設定
getp()Artist 属性を取得(get のエイリアス)
get_current_fig_manager()現在の Figure マネージャーを取得
new_figure_manager()Figure のマネージャーを作成
set_loglevel()ログレベルを設定
xkcd()xkcd の手書き漫画スタイルに切り替え

イベント処理 - connect() / disconnect()

matplotlib.pyplot.connect(s, func)
matplotlib.pyplot.disconnect(cid)

例

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(np.random.randn(50).cumsum())
ax.set_title('Click anywhere on the figure')

# クリックイベントのコールバック
def on_click(event):
    print(f'Clicked at: x={event.xdata:.2f}, y={event.ydata:.2f}')

# イベントをバインド
cid = fig.canvas.mpl_connect('button_press_event', on_click)

plt.show()
print("サンプル: click events registered")

ginput() - マウスで座標を選択

matplotlib.pyplot.ginput(n=1, timeout=30, show_clicks=True,
    mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT,
    mouse_stop=MouseButton.MIDDLE)

例

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(7, 5))
ax.plot(np.arange(10), np.random.randn(10), 'o-')
ax.set_title('Click 3 points (timeout=15s)')
ax.set_xlim(-1, 10)
ax.set_ylim(-3, 3)
ax.grid(True, alpha=0.3)

print("Please click 3 points...")
points = plt.ginput(3, timeout=15, show_clicks=True)

for i, (x, y) in enumerate(points):
    print(f"Point {i+1}: ({x:.2f}, {y:.2f})")

plt.show()

waitforbuttonpress() - キー入力を待つ

matplotlib.pyplot.waitforbuttonpress(timeout=-1)

戻り値:True はキーボードが押されたこと、False はマウスが押されたことを示します。

例

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot(np.sin(np.linspace(0, 10, 100)))
ax.set_title('Press any key or click mouse')

print("Waiting for button press...")
result = plt.waitforbuttonpress(timeout=10)
if result is None:
    print("Timeout!")
elif result:
    print("Key was pressed")
else:
    print("Mouse was clicked")

plt.show()

findobj() - Artist を検索

matplotlib.pyplot.findobj(o=None, match=None, include_self=False)

例

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6], label='Line A')
ax.plot([1, 2, 3], [1, 2, 3], label='Line B')
ax.set_title('Find Objects Demo')

# すべての Line2D オブジェクトを検索
lines = ax.findobj(match=Line2D)
print(f"Found {len(lines)} line objects")

# 特定の属性を取得
for line in lines:
    print(f"  - label: {line.get_label()}")

# get() を使用して属性を取得
ax_title = ax.get_title()
print(f"Axes title: {ax_title}")

plt.show()
Found 2 line objects
  - label: Line A
  - label: Line B
Axes title: Find Objects Demo

get() / setp() - 属性操作

matplotlib.pyplot.get(obj, *args, **kwargs)
matplotlib.pyplot.setp(obj, *args, **kwargs)
matplotlib.pyplot.getp(obj, *args, **kwargs)

例

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(layout='constrained')
line, = ax.plot([0, 1], [0, 1], label='test')

# get() で単一の属性を取得
print("line color:", plt.get(line, 'color'))

# getp() で複数の属性を取得
props = plt.getp(line)
print(f"line has {len(props)} properties")

# setp() で属性を一括設定
plt.setp(line, color='red', linewidth=3, linestyle='--')

ax.set_title('setp() demo')
ax.legend()
plt.show()
print("サンプル: properties modified via setp()")

xkcd() - 手書き漫画スタイル

matplotlib.pyplot.xkcd(scale=1, length=100, randomness=2)

例

import matplotlib.pyplot as plt
import numpy as np

# xkcd の手書きスタイルを有効にする
with plt.xkcd():
    fig, ax = plt.subplots(figsize=(8, 5))
    x = np.linspace(0, 10, 100)
    ax.plot(x, np.sin(x), label='sin(x)')
    ax.plot(x, np.cos(x), label='cos(x)')
    ax.set_title('XKCD-style Plot')
    ax.set_xlabel('Time')
    ax.set_ylabel('Amplitude')
    ax.legend()
    ax.annotate('This is peak!',
                xy=(np.pi/2, 1), xytext=(2, 1.3),
                arrowprops=dict(arrowstyle='->'))
    plt.show()
    print("サンプル: xkcd style displayed")

set_loglevel() - ログレベル

matplotlib.pyplot.set_loglevel(level)

level のオプション: 'debug', 'info', 'warning', 'error', 'critical'。

例

import matplotlib.pyplot as plt
import numpy as np

# ログレベルを info に設定(Matplotlib の内部情報を表示)
plt.set_loglevel('info')

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Debugging with loglevel')

plt.show()

Matplotlib 参考文档Matplotlib リファレンスドキュメント

その他の拡張機能