Pythonのデータビジュアライゼーションライブラリであるmatplotlibを用いて、グラフの一部を拡大表示する方法について説明します。
グラフの一部を拡大表示する
まずは、全体のグラフを描画します。その後、同じデータを用いて一部を拡大したグラフを描画します。以下にそのコードを示します。
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(2, 1)
x = np.arange(0.0, 10.0, 0.01)
y = np.sin(2 * x) + 0.1
axes[0].plot(x, y)
axes[1].plot(x, y)
axes[1].set_xlim(0.5, 6)
axes[1].set_ylim(0, 1.25)
plt.show()
全体図に拡大部分を図示する
次に、全体図に拡大部分を図示します。これには、Rectangle
オブジェクトを生成し、全体図に対してadd_patch()
します。
import matplotlib.patches as patches
xlim = axes[1].get_xlim()
ylim = axes[1].get_ylim()
rect = patches.Rectangle([xlim[0], ylim[0]], xlim[1] - xlim[0], ylim[1] - ylim[0])
axes[0].add_patch(rect)
拡大部分をマウスで動的に変更する
最後に、mpl_connect()
を使って、マウス操作に関するイベントを取得できるようにします。ドラッグ操作に対応して四角を動かし、連動して拡大図の表示範囲を変更します。
def on_button_down(event):
global press
if event.inaxes != axes[0] or event.button != 1:
return
press = True
def on_button_up(event):
global press
press = False
def on_mouse_move(event):
global fig, axes, press, rect
if not press or event.inaxes != axes[0]:
return
dx = event.xdata - rect.get_x()
dy = event.ydata - rect.get_y()
rect.set_x(rect.get_x() + dx)
rect.set_y(rect.get_y() + dy)
axes[1].set_xlim([rect.get_x(), rect.get_x() + rect.get_width()])
axes[1].set_ylim([rect.get_y(), rect.get_y() + rect.get_height()])
fig.canvas.draw()
fig.canvas.mpl_connect('button_press_event', on_button_down)
fig.canvas.mpl_connect('button_release_event', on_button_up)
fig.canvas.mpl_connect('motion_notify_event', on_mouse_move)
以上がPythonとmatplotlibを用いて、グラフの一部を拡大表示する方法です。この方法を用いることで、データの特定の部分に焦点を当てて詳細な分析を行うことが可能になります。.