【发布时间】:2014-01-06 11:56:41
【问题描述】:
我试图修改我在 stackoverflow 论坛上找到的一些代码(How can I plot the same figure standalone and in a subplot in Matplotlib? 第一个答案)。
它的基本作用是在单击子图时放大子图(仅在画布上显示单击的子图),并在再次单击时缩小(在画布上显示所有子图)。我尝试修改代码以通过多种方式将其调整为我的程序,但是我一直遇到同样的问题。正确创建了带有子图的图形画布并输入了缩放子图类,但它似乎与我的点击事件没有联系(它没有输入“on_click”)。
我试图找出问题所在并尝试了几次修改,但仍然遇到同样的问题。我无法使用我从中检索到的主题中显示的代码,因为它不适合我的程序的其余部分。
import numpy as np
from matplotlib import pyplot as plt
class ZoomingSubplots(object):
''' zoom to subplot if subplot is clicked, unzoom when clicked again'''
def __init__(self, fig):
print 'class entered'
self.fig = fig
self.fig.canvas.mpl_connect('button_press_event', self.on_click)
def zoom(self, selected_ax):
for ax in self.axes.flat:
ax.set_visible(False)
self._original_size = selected_ax.get_position()
selected_ax.set_position([0.125, 0.1, 0.775, 0.8])
selected_ax.set_visible(True)
self._zoomed = True
def unzoom(self, selected_ax):
selected_ax.set_position(self._original_size)
for ax in self.axes.flat:
ax.set_visible(True)
self._zoomed = False
def on_click(self, event):
print 'click event'
if event.inaxes is None:
return
if self._zoomed:
self.unzoom(event.inaxes)
else:
self.zoom(event.inaxes)
self.fig.canvas.draw()
#make a figure with 9 random imshows
plots = 9 #number of plots
plotrows = 3 #subplot rows
plotcols = 3 #subplot columns
fig = plt.figure()
for i in range(plots):
arr = np.random.rand(10,10)
ax = fig.add_subplot(plotrows, plotcols, i+1)
ax.imshow(arr, interpolation = 'nearest')
ax.set_title('%s %i' % ('plot', i+1), fontsize = 10)
# connect with zoom class
ZoomingSubplots(fig)
plt.show()
A 将其调整为更简单的代码,您可以在其中发现同样的问题:
import numpy as np
from matplotlib import pyplot as plt
class ZoomingSubplots(object):
def __init__(self, fig):
print 'class entered'
self.fig = fig
self.fig.canvas.mpl_connect('button_press_event', self.on_click)
def on_click(self, event):
print 'click event'
#make a figure with 9 random imshows
fig = plt.figure()
for i in range(9):
arr = np.random.rand(10,10)
ax = fig.add_subplot(3, 3, i+1)
ax.imshow(arr, interpolation = 'nearest')
# connect with zoom class
ZoomingSubplots(fig)
plt.show()
【问题讨论】:
标签: python matplotlib