gpt4 book ai didi

python - matplotlib SpanSelector 小部件 : how to use inside a function?

转载 作者:太空宇宙 更新时间:2023-11-03 18:56:45 25 4
gpt4 key购买 nike

我正在尝试在函数内使用 matplotlib SpanSelector 。我修改了原始示例( http://matplotlib.org/examples/widgets/span_selector.html ),但它不起作用。这是代码:

#!/usr/bin/env python
"""
The SpanSelector is a mouse widget to select a xmin/xmax range and plot the
detail view of the selected region in the lower axes
"""
import numpy as npy
from pylab import figure, show
from matplotlib.widgets import SpanSelector

fig = figure(figsize=(8,6))
ax = fig.add_subplot(211, axisbg='#FFFFCC')

x = npy.arange(0.0, 5.0, 0.01)
y = npy.sin(2*npy.pi*x) + 0.5*npy.random.randn(len(x))

ax.plot(x, y, '-')
ax.set_ylim(-2,2)
ax.set_title('Press left mouse button and drag to test')

ax2 = fig.add_subplot(212, axisbg='#FFFFCC')
line2, = ax2.plot(x, y, '-')


def onselect(xmin, xmax):
indmin, indmax = npy.searchsorted(x, (xmin, xmax))
indmax = min(len(x)-1, indmax)

thisx = x[indmin:indmax]
thisy = y[indmin:indmax]
line2.set_data(thisx, thisy)
ax2.set_xlim(thisx[0], thisx[-1])
ax2.set_ylim(thisy.min(), thisy.max())
fig.canvas.draw()

## set useblit True on gtkagg for enhanced performance
# SpanSelector works this way
#span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
# rectprops=dict(alpha=0.5, facecolor='red') )

def fun_with_spanselector_inside():
# set useblit True on gtkagg for enhanced performance
span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
rectprops=dict(alpha=0.5, facecolor='red') )

# SpanSelector does not work this way
fun_with_spanselector_inside()

show()

我在 Ubuntu 12.04 上使用 Python 2.7、matplotlib 1.1.1rc。

为什么这不起作用?

最佳答案

您只需保留对 SpanSelector 实例的引用即可。否则,它将被垃圾收集。

基本上,您需要这样做:

def fun_with_spanselector_inside():
# set useblit True on gtkagg for enhanced performance
span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
rectprops=dict(alpha=0.5, facecolor='red') )
return span

span = fun_with_spanselector_inside()

请注意,这与它在函数内部无关。如果你这样做:

SpanSelector(ax, onselect, 'horizontal', useblit=True,
rectprops=dict(alpha=0.5, facecolor='red'))

这也行不通。

不过,这在文档中应该更清楚。我不确定这是有意为之还是意外。

关于python - matplotlib SpanSelector 小部件 : how to use inside a function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17111859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com