本文整理汇总了Python中matplotlib.patches.Rectangle.set_visible方法的典型用法代码示例。如果您正苦于以下问题:Python Rectangle.set_visible方法的具体用法?Python Rectangle.set_visible怎么用?Python Rectangle.set_visible使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.patches.Rectangle
的用法示例。
在下文中一共展示了Rectangle.set_visible方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
def __init__(self, ax, labels, actives):
"""
Add check buttons to :class:`matplotlib.axes.Axes` instance *ax*
*labels*
A len(buttons) list of labels as strings
*actives*
A len(buttons) list of booleans indicating whether
the button is active
"""
ax.set_xticks([])
ax.set_yticks([])
ax.set_navigate(False)
if len(labels)>1:
dy = 1./(len(labels)+1)
ys = np.linspace(1-dy, dy, len(labels))
else:
dy = 0.25
ys = [0.5]
cnt = 0
axcolor = ax.get_axis_bgcolor()
self.labels = []
self.lines = []
self.rectangles = []
lineparams = {'color':'k', 'linewidth':1.25, 'transform':ax.transAxes,
'solid_capstyle':'butt'}
for y, label in zip(ys, labels):
t = ax.text(0.25, y, label, transform=ax.transAxes,
horizontalalignment='left',
verticalalignment='center')
w, h = dy/2., dy/2.
x, y = 0.05, y-h/2.
p = Rectangle(xy=(x,y), width=0.9, height=h, facecolor=axcolor,transform=ax.transAxes)
l1 = Rectangle(xy=(x,y), width=0.9, height=h, facecolor='red',alpha=0.5, transform=ax.transAxes)
l1.set_visible(actives[cnt])
#l2.set_visible(actives[cnt])
self.labels.append(t)
self.rectangles.append(p)
self.lines.append((l1))#,l2))
ax.add_patch(p)
ax.add_patch(l1)
#ax.add_line(l2)
cnt += 1
ax.figure.canvas.mpl_connect('button_press_event', self._clicked)
self.ax = ax
self.cnt = 0
self.observers = {}
示例2: _init_rectangles
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
def _init_rectangles(self):
self.rectangles = []
n_row = len(self.axes)
for row_i, all_axes in enumerate(self.axes):
self.rectangles.append([])
for col_i, axes in enumerate(all_axes):
rect = Rectangle( (0, 0), 0, 0 )
rect.set_visible(False)
axes.add_patch(rect)
self.rectangles[-1].append(rect)
return
示例3: MplYRangeROI
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
class MplYRangeROI(AbstractMplRoi):
def __init__(self, ax):
"""
:param ax: A matplotlib Axes object to attach the graphical ROI to
"""
AbstractMplRoi.__init__(self, ax)
self._xi = None
self.plot_opts = {'edgecolor': PATCH_COLOR, 'facecolor': PATCH_COLOR,
'alpha': 0.3}
trans = blended_transform_factory(self._ax.transAxes,
self._ax.transData)
self._patch = Rectangle((0., 0.), 1., 1., transform=trans)
self._patch.set_zorder(100)
self._setup_patch()
def _setup_patch(self):
self._ax.add_patch(self._patch)
self._patch.set_visible(False)
self._sync_patch()
def _roi_factory(self):
return YRangeROI()
def start_selection(self, event):
if event.inaxes != self._ax:
return
self._roi.reset()
self._roi.set_range(event.ydata, event.ydata)
self._xi = event.ydata
self._mid_selection = True
self._sync_patch()
def update_selection(self, event):
if not self._mid_selection or event.inaxes != self._ax:
return
self._roi.set_range(min(event.ydata, self._xi),
max(event.ydata, self._xi))
self._sync_patch()
def finalize_selection(self, event):
self._mid_selection = False
self._patch.set_visible(False)
self._draw()
def _sync_patch(self):
if self._roi.defined():
rng = self._roi.range()
self._patch.set_xy((0, rng[0]))
self._patch.set_height(rng[1] - rng[0])
self._patch.set_width(1)
self._patch.set(**self.plot_opts)
self._patch.set_visible(True)
else:
self._patch.set_visible(False)
self._draw()
示例4: PlotInterface
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
class PlotInterface(object):
def __init__(self, df, EvT_color_set, EvT_size_set):
self.df = df
self.ax = plt.gca()
self.rect = Rectangle((0.1,0.1), 0, 0, fill=False)
self.rect.set_visible(False)
self.ax.add_patch(self.rect)
self.x0 = None
self.y0 = None
self.x1 = None
self.y1 = None
self.press = False
self.sub_df = None
self.EvT_color_set = EvT_color_set
self.EvT_size_set = EvT_size_set
self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
self.ax.figure.canvas.mpl_connect('motion_notify_event',self.on_motion)
self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
def on_press(self, event):
if event.inaxes:
self.press = True
self.x0 = event.xdata
self.y0 = event.ydata
self.rect.set_width(0)
self.rect.set_height(0)
self.rect.set_xy((self.x0,self.y0))
self.rect.set_visible(True)
#Save the plot background
self.background = self.ax.figure.canvas.copy_from_bbox(self.ax.bbox)
def on_release(self, event):
if event.inaxes:
self.press = False
self.x1 = event.xdata
self.y1 = event.ydata
self.rect.set_visible(False)
self.ax.figure.canvas.draw()
self.min_x = min(self.x0,self.x1)
self.max_x = max(self.x0,self.x1)
self.min_y = min(self.y0,self.y1)
self.max_y = max(self.y0,self.y1)
if self.sub_df is not None:
self.sub_df = self.sub_df.append(self.df[ (self.df['timestamp'] > self.min_x) & (self.df['timestamp'] < self.max_x) & \
(self.df['amplitude'] > self.min_y) & (self.df['amplitude'] < self.max_y)])
else:
self.sub_df = self.df[ (self.df['timestamp'] > self.min_x) & (self.df['timestamp'] < self.max_x) & \
(self.df['amplitude'] > self.min_y) & (self.df['amplitude'] < self.max_y)]
plt.scatter(self.sub_df['timestamp'],self.sub_df['amplitude'],color='blue',s=self.EvT_size_set)
self.ax.figure.canvas.draw()
print('Selected (%d < timestamp < %d) and (%d < amplitude < %d)' % (self.min_x, self.max_x, self.min_y, self.max_y))
def on_motion(self, event):
if self.press is False: return
if event.inaxes != self.rect.axes: return
self.x1 = event.xdata
self.y1 = event.ydata
self.rect.set_width(self.x1 - self.x0)
self.rect.set_height(self.y1 - self.y0)
self.rect.set_xy((self.x0, self.y0))
self.ax.figure.canvas.restore_region(self.background)
self.ax.draw_artist(self.rect)
self.ax.figure.canvas.blit(self.rect.clipbox)
示例5: __init__
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
class RangeSelector:
def __init__(self, axes, callbackPre, callbackPost):
self.axes = axes
self.callbackPre = callbackPre
self.callbackPost = callbackPost
self.eventPressed = None
self.eventReleased = None
props = dict(facecolor="red", edgecolor="white", alpha=0.25, fill=True, zorder=100, gid="range")
self.rect = Rectangle((0, 0), 0, 0, **props)
self.axes.add_patch(self.rect)
figure = self.axes.get_figure()
figure.canvas.mpl_connect("motion_notify_event", self.__on_move)
figure.canvas.mpl_connect("button_press_event", self.__on_press)
figure.canvas.mpl_connect("button_release_event", self.__on_release)
def __on_press(self, event):
if self.__skip_event(event):
return
self.eventPressed = event
self.callbackPre()
self.rect.set_visible(True)
return
def __on_move(self, event):
if self.eventPressed is None or self.__skip_event(event):
return
xMin = self.eventPressed.xdata
xMax = event.xdata
if xMin > xMax:
xMin, xMax = xMax, xMin
self.callbackPost(xMin, xMax)
return
def __on_release(self, event):
if self.eventPressed is None or self.__skip_event(event):
return
self.eventReleased = event
xMin, xMax = self.eventPressed.xdata, self.eventReleased.xdata
if xMin > xMax:
xMin, xMax = xMax, xMin
self.callbackPost(xMin, xMax)
self.eventPressed = None
self.eventReleased = None
return
def __skip_event(self, event):
if event.button != 2:
return True
if self.eventPressed is None:
return event.inaxes != self.axes
if event.button == self.eventPressed.button and event.inaxes != self.axes:
transform = self.axes.transData.inverted()
(x, _y) = transform.transform_point((event.x, event.y))
x0, x1 = self.axes.get_xbound()
x = max(x0, x)
x = min(x1, x)
event.xdata = x
return False
return event.inaxes != self.axes or event.button != self.eventPressed.button
def draw(self, xMin, xMax):
self.rect.set_visible(True)
yMin, yMax = self.axes.get_ylim()
height = yMax - yMin
yMin -= height * 100.0
yMax += height * 100.0
self.rect.set_x(xMin)
self.rect.set_y(yMin)
self.rect.set_width(xMax - xMin)
self.rect.set_height(yMax - yMin)
if self.axes._cachedRenderer is not None:
self.axes.draw_artist(self.rect)
def hide(self):
self.rect.set_visible(False)
def clear(self):
self.rect.set_visible(False)
canvas = self.axes.get_figure().canvas
canvas.draw()
示例6: CaseSelector
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
#.........这里部分代码省略.........
self.canvas = None
self.new_axes(ax, nrect)
def new_axes(self, ax, nrect):
self.ax = ax
if self.canvas is not ax.figure.canvas:
if self.canvas is not None:
self.disconnect_events()
self.canvas = ax.figure.canvas
self.connect_default_events()
# span
trans = blended_transform_factory(self.ax.transData, self.ax.transAxes)
w, h = 0, 1
self.rect = Rectangle((0, 0), w, h, transform=trans, visible=False,
animated=True, **self.rectprops)
self.ax.add_patch(self.rect)
self.artists = [self.rect]
# stay rect
self.stay_rects = []
for set in range(0, len(nrect)):
self.stay_rects.append([])
for n in range(0, nrect[set]):
stay_rect = Rectangle((0, 0), w, h, transform=trans, visible=False,
animated=True, **self.stay_rectprops[set])
self.ax.add_patch(stay_rect)
self.stay_rects[set].append(stay_rect)
self.artists.extend(self.stay_rects[set])
# bar
self.bar = ax.axvline(0, w, h, visible=False, **self.lineprops)
self.artists.append(self.bar)
def set_bar_position(self, x):
self.bar.set_xdata(x)
self.bar.set_visible(True)
def set_stay_rects_x_bounds(self, xarr, set=0):
for n, stay_rect in enumerate(self.stay_rects[set]):
try:
xmin, xmax = xarr[n]
except IndexError:
stay_rect.set_visible(False)
else:
stay_rect.set_x(xmin)
stay_rect.set_y(self.rect.get_y())
stay_rect.set_width(abs(xmax - xmin))
stay_rect.set_height(self.rect.get_height())
stay_rect.set_visible(True)
def set_stay_rect_visible(self, b=True, set=0):
for stay_rect in self.stay_rects[set]:
stay_rect.set_visible(b)
def ignore(self, event):
"""return *True* if *event* should be ignored"""
return _SelectorWidget.ignore(self, event) or not self.visible
def _press(self, event):
"""on button press event"""
xdata, ydata = self._get_data(event)
self.pressv = xdata
return False
def _release(self, event):
"""on button release event"""
if self.pressv is None:
return
示例7: Annotate
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
#.........这里部分代码省略.........
# imgplot = plt.imshow(patch)
# plt.show()
plt.close()
def colorChange(self,event):
'''
To change color to take false positves into consideration - the default is color blue for true postive
'''
print('press', event.key)
sys.stdout.flush()
if event.key == 'r': # red color
# When 'r' key is pressed, the color of the next patch will be red
self.col = 'r'
elif event.key == 'b': # blue color
# When 'b' key is pressed, the color of the next patch will be blue
self.col = 'b'
# Optional setting for drawing patched using spacebar
# elif event.key == ' ':
# self.on_click(event)
elif event.key == 'd': # delete
# When 'd' key is pressed, the latest patch drawn is deleted
#self.deletePrevious()
nr = self.objList[-1]
nr.set_visible(False)
elif event.key == 'c': # clear
# When 'c' key is pressed, all the patches are cleared, only orignal background is present
self.blit()
self.xy = []
# Flush out the list as we don't want to consider any patch co-ordinates
elif event.key == 'tab':
# use tab to increase the aspect ratio of the patch
self.resize(1.2)
elif event.key == 'control':
# use control key to decrease the aspect ratio of the patch
self.resize(0.95)
elif event.key == '2':
# use control key to decrease the aspect ratio of the patch
self.resize(0.85)
elif event.key == '3':
# use control key to decrease the aspect ratio of the patch
self.resize(0.50)
elif event.key == 'q': # quit plot, show up the next
# save necessary labels and close the plot
self.qkey = 'q'
self.close_plot()
elif event.key == '0':
示例8: __init__
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
class Selector:
def __init__(self, filenames):
self.filenames = filenames
try:
self.filename = next(self.filenames)
except:
print("No more images to be labelled")
self.image = Image.open(RAW_FOLDER + self.filename)
print("Labeling", self.filename)
self.counter = 0
self.fig, self.ax = plt.subplots(1, 1, figsize=(14, 8))
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
self.x = [0, 0]
self.y = [0, 0]
self.samples = {}
self.on = False
self.hasNext = True
self.options = None
self.ax.imshow(self.image)
self.rect = Rectangle((0,0), 0, 0, fill=None, linewidth=2, color="r")
self.ax.add_patch(self.rect)
self.ax.figure.canvas.mpl_connect('button_press_event', self.press)
self.ax.figure.canvas.mpl_connect('motion_notify_event', self.move)
self.ax.figure.canvas.mpl_connect('button_release_event', self.release)
self.fig.canvas.mpl_connect('key_press_event', self.terminate)
self.fig.canvas.mpl_connect('close_event', self.close)
plt.show()
def terminate(self, event):
"""
x: close and save
c: close without saving
"""
if event.key:
if event.key == "x":
self.hasNext = False
plt.close()
self.close()
elif event.key == "c":
plt.close()
def press(self, event):
"""
Mouse click event
"""
if (-1 < event.xdata < self.image.size[0]) and (-1 < event.ydata < self.image.size[1]):
self.on = True
self.x[0], self.y[0] = event.xdata, event.ydata
self.rect.set_visible(True)
self.rect.set_animated(True)
self.fig.canvas.draw()
self.background = self.fig.canvas.copy_from_bbox(self.rect.axes.bbox)
self.ax.draw_artist(self.rect)
self.fig.canvas.blit(self.ax.bbox)
def move(self, event):
"""
Mousemove event
"""
if self.on:
if event.xdata is not None and event.ydata is not None:
self.x[1], self.y[1] = event.xdata, event.ydata
self.rect.set_width(abs(self.x[1] - self.x[0]))
self.rect.set_height(abs(self.y[1] - self.y[0]))
self.rect.set_xy((min(self.x), min(self.y)))
self.fig.canvas.restore_region(self.background)
self.ax.draw_artist(self.rect)
self.fig.canvas.blit(self.ax.bbox)
def release(self, event):
"""
Mouse release event
"""
if self.on:
self.on = False
self.background = None
if self.options is not None:
self.options.window.destroy()
self.options = Select()
self.options.window.mainloop()
self.rect.set_width(0)
self.rect.set_height(0)
self.rect.set_visible(False)
self.fig.canvas.draw()
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
#.........这里部分代码省略.........
residuals = self.profile - fitprof
plt.plot(self.phases, residuals, 'k')
plt.xlabel('Pulse Phase')
plt.ylabel('Data-Fit Residuals')
plt.draw()
self.eventpress = None
# will save the data (pos. at mouserelease)
self.eventrelease = None
def update_background(self, event):
"""force an update of the background"""
if self.useblit:
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
def ignore(self, event):
"""return True if event should be ignored"""
# If no button was pressed yet ignore the event if it was out
# of the axes
if self.eventpress == None:
return event.inaxes != self.ax
# If a button was pressed, check if the release-button is the
# same.
return (event.inaxes != self.ax or
event.button != self.eventpress.button)
def press(self, event):
"""on button press event"""
# Is the correct button pressed within the correct axes?
if self.ignore(event): return
# make the drawed box/line visible get the click-coordinates,
# button, ...
self.eventpress = event
if event.button == 1:
self.to_draw.set_visible(self.visible)
self.eventpress.ydata = self.DCguess
def release(self, event):
"""on button release event"""
if self.eventpress is None or self.ignore(event): return
# release coordinates, button, ...
self.eventrelease = event
if event.button == 1:
# make the box/line invisible again
self.to_draw.set_visible(False)
self.canvas.draw()
xmin, ymin = self.eventpress.xdata, self.eventpress.ydata
xmax, ymax = self.eventrelease.xdata, self.eventrelease.ydata
# calculate dimensions of box
if xmin > xmax: xmin, xmax = xmax, xmin
if ymin > ymax: ymin, ymax = ymax, ymin
spanx = xmax - xmin
spany = ymax - ymin
xproblems = self.minspanx is not None and spanx < self.minspanx
yproblems = self.minspany is not None and spany < self.minspany
# call desired function
self.onselect()
self.eventpress = None # reset the variables to their
self.eventrelease = None # inital values
def update(self):
"""draw using blit or old draw depending on useblit"""
if self.useblit:
if self.background is not None:
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.to_draw)
self.canvas.blit(self.ax.bbox)
示例10: MatplotlibViewerMixin
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
class MatplotlibViewerMixin(object):
def setup_callbacks(self):
for spine in self.axes.spines.values():
spine.set_zorder(ZORDER_MAX)
self.loading_rectangle = Rectangle((0, 0), 1, 1, color='0.9', alpha=0.9,
zorder=ZORDER_MAX - 1, transform=self.axes.transAxes)
self.loading_rectangle.set_visible(False)
self.axes.add_patch(self.loading_rectangle)
self.loading_text = self.axes.text(0.4, 0.5, 'Computing', color='k',
zorder=self.loading_rectangle.get_zorder() + 1,
ha='left', va='center',
transform=self.axes.transAxes)
self.loading_text.set_visible(False)
self.state.add_callback('aspect', self.update_aspect)
self.update_aspect()
self.state.add_callback('x_min', self.limits_to_mpl)
self.state.add_callback('x_max', self.limits_to_mpl)
self.state.add_callback('y_min', self.limits_to_mpl)
self.state.add_callback('y_max', self.limits_to_mpl)
self.limits_to_mpl()
self.state.add_callback('x_log', self.update_x_log, priority=1000)
self.state.add_callback('y_log', self.update_y_log, priority=1000)
self.update_x_log()
self.axes.callbacks.connect('xlim_changed', self.limits_from_mpl)
self.axes.callbacks.connect('ylim_changed', self.limits_from_mpl)
self.axes.set_autoscale_on(False)
self.state.add_callback('x_axislabel', self.update_x_axislabel)
self.state.add_callback('x_axislabel_weight', self.update_x_axislabel)
self.state.add_callback('x_axislabel_size', self.update_x_axislabel)
self.state.add_callback('y_axislabel', self.update_y_axislabel)
self.state.add_callback('y_axislabel_weight', self.update_y_axislabel)
self.state.add_callback('y_axislabel_size', self.update_y_axislabel)
self.state.add_callback('x_ticklabel_size', self.update_x_ticklabel)
self.state.add_callback('y_ticklabel_size', self.update_y_ticklabel)
self.update_x_axislabel()
self.update_y_axislabel()
self.update_x_ticklabel()
self.update_y_ticklabel()
def _update_computation(self, message=None):
pass
def update_x_axislabel(self, *event):
self.axes.set_xlabel(self.state.x_axislabel,
weight=self.state.x_axislabel_weight,
size=self.state.x_axislabel_size)
self.redraw()
def update_y_axislabel(self, *event):
self.axes.set_ylabel(self.state.y_axislabel,
weight=self.state.y_axislabel_weight,
size=self.state.y_axislabel_size)
self.redraw()
def update_x_ticklabel(self, *event):
self.axes.tick_params(axis='x', labelsize=self.state.x_ticklabel_size)
self.axes.xaxis.get_offset_text().set_fontsize(self.state.x_ticklabel_size)
self.redraw()
def update_y_ticklabel(self, *event):
self.axes.tick_params(axis='y', labelsize=self.state.y_ticklabel_size)
self.axes.yaxis.get_offset_text().set_fontsize(self.state.y_ticklabel_size)
self.redraw()
def redraw(self):
self.figure.canvas.draw()
def update_x_log(self, *args):
self.axes.set_xscale('log' if self.state.x_log else 'linear')
self.redraw()
def update_y_log(self, *args):
self.axes.set_yscale('log' if self.state.y_log else 'linear')
self.redraw()
def update_aspect(self, aspect=None):
self.axes.set_aspect(self.state.aspect, adjustable='datalim')
@avoid_circular
def limits_from_mpl(self, *args):
with delay_callback(self.state, 'x_min', 'x_max', 'y_min', 'y_max'):
if isinstance(self.state.x_min, np.datetime64):
#.........这里部分代码省略.........
示例11: LassoSelection
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
class LassoSelection(PolygonToolBase):
def __init__(self, ax, on_move=None, on_release=None, on_enter=None,
useblit=True, line_props=None):
super(LassoSelection, self).__init__(ax, on_move=on_move,
on_release=on_release,
on_enter=on_enter,
useblit=useblit,
line_props=line_props)
self.shape = 'lasso'
self.mode = 'lasso'
self._prev_angle = 1e6
self._indicator = Rectangle((0, 0), 0, 0)
self._indicator.set_visible(False)
ax.add_patch(self._indicator)
self._artists.append(self._indicator)
def on_move(self, event):
if self.verts is None or not self._busy:
return
if self.mode == 'polygon':
self.verts[-1] = (event.xdata, event.ydata)
else:
# see if we are moving in the same direction
point2 = (event.xdata, event.ydata)
point1 = np.asarray(self.verts[-1], dtype=float)
point2 = np.asarray(point2, dtype=float)
dx, dy = point2 - point1
theta = np.arctan2(dy, dx)
if theta == self._prev_angle:
self.verts[-1] = (event.xdata, event.ydata)
else:
self.verts.append((event.xdata, event.ydata))
self._prev_angle = theta
try:
self._show_indicator()
except TypeError:
pass
self.update()
def on_mouse_release(self, event):
self.mode = 'polygon'
def on_mouse_press(self, event):
if self._indicator.get_visible() or event.dblclick:
self.verts = self.verts[:-1]
self.finalize()
return
if not self._busy:
self.start(event)
self.mode = 'lasso'
self.verts.append((event.xdata, event.ydata))
self.update()
def start(self, event):
super(LassoSelection, self).start(event)
self._prev_angle = 1e6
def finalize(self):
self.verts.append(self.verts[0])
self._indicator.set_visible(False)
super(LassoSelection, self).finalize()
def _show_indicator(self):
if not self.verts:
return
bounds = self.ax.dataLim.bounds
wid = float(bounds[2] - bounds[0])
hgt = float(bounds[3] - bounds[1])
orig = self.verts[0]
curr = self.verts[-1]
# see if we are within 2% in x and y
if (abs(curr[0] - orig[0]) / wid < 0.02 and
abs(curr[1] - orig[1]) / hgt < 0.02):
wid /= 100.
hgt /= 100.
self._indicator.set_xy((orig[0] - wid / 2.,
orig[1] - hgt / 2.))
self._indicator.set_width(wid * 2)
self._indicator.set_height(hgt * 2)
if not self._indicator.get_visible():
self._indicator.set_visible(True)
self.redraw()
elif self._indicator.get_visible():
self._indicator.set_visible(False)
self.redraw()
@property
def geometry(self):
return self.verts
@geometry.setter
def geometry(self, verts):
self.verts = verts
self.update()
示例12: Annotate
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
#.........这里部分代码省略.........
elif event.key == 'q': # quit plot, show up the next
# save necessary labels and close the plot
self.qkey = 'q'
self.close_plot()
elif event.key == '0':
sys.exit()
def on_click(self, event):
'''
Using two diagonally opposite clicks to draw a reactangle
'''
self.i = self.i + 1
if self.i%2 == 0:
# The first click to mark one point of the rectangle and save the coordinates
print 'click1'
self.mx0 = event.xdata
self.my0 = event.ydata
if self.i%2 == 1:
# on second click - the rectangle should show up
print 'click2'
self.mx1 = event.xdata
self.my1 = event.ydata
self.drawRect()
def drawRect(self):
self.mx0, self.y0 = (self.mx0, self.my0) if (self.my1>self.my0) else (self.mx1,self.my1)
self.mx1, self.y1 = (self.mx0, self.my0) if (self.my1<self.my0) else (self.mx1,self.my1)
# Set the two diagonally opposite co-ordinates of the patch by width and height
self.height = self.y1 - self.y0
self.width = 3.0/4.0 * self.height
self.x0 = self.mx0 - self.width/2
self.x1 = self.mx0 + self.width/2
print self.x0, self.x1
self.xy.append([self.x0,self.y0,self.x1,self.y1,self.col])
print self.xy
# Set the width and height of the rectangle patch as these two alone can characterize the patch
self.rect.set_width(self.width)
self.rect.set_height(self.height)
self.rect.set_xy((self.x0, self.y0))
# Set the color of the reactangle - can be blue/red depending on postive/negative label respectively
self.rect.set_color(self.col)
self.ax.draw_artist(self.rect)
# Blit is used to successively retain and display patches on the screen
# Else Successively drawing one patch will remove the last drawn patch
self.ax.figure.canvas.blit(self.ax.bbox)
# The following three functions taken from
# http://stackoverflow.com/questions/29277080/efficient-matplotlib-redrawing
def safe_draw(self):
"""Temporarily disconnect the draw_event callback to avoid recursion"""
canvas = self.ax.figure.canvas
canvas.mpl_disconnect(self.draw_cid)
canvas.draw()
self.draw_cid = canvas.mpl_connect('draw_event', self.grab_background)
def grab_background(self, event=None):
"""
When the figure is resized, hide the rect, draw everything,
and update the background.
"""
self.rect.set_visible(False)
self.safe_draw()
# With most backends (e.g. TkAgg), we could grab (and refresh, in
# self.blit) self.ax.bbox instead of self.fig.bbox, but Qt4Agg, and
# some others, requires us to update the _full_ canvas, instead.
self.background = self.ax.figure.canvas.copy_from_bbox(self.ax.figure.bbox)
self.rect.set_visible(True)
# self.blit()
def blit(self):
"""
Efficiently update the figure, without needing to redraw the
"background" artists.
"""
self.objCreation()
self.ax.figure.canvas.restore_region(self.background)
self.ax.draw_artist(self.rect)
self.ax.figure.canvas.blit(self.ax.figure.bbox)
示例13: MatplotlibDataViewer
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
class MatplotlibDataViewer(DataViewer):
_state_cls = MatplotlibDataViewerState
tools = ['mpl:home', 'mpl:pan', 'mpl:zoom']
subtools = {'save': ['mpl:save']}
def __init__(self, session, parent=None, wcs=None, state=None):
super(MatplotlibDataViewer, self).__init__(session, parent=parent, state=state)
# Use MplWidget to set up a Matplotlib canvas inside the Qt window
self.mpl_widget = MplWidget()
self.setCentralWidget(self.mpl_widget)
# TODO: shouldn't have to do this
self.central_widget = self.mpl_widget
self.figure, self._axes = init_mpl(self.mpl_widget.canvas.fig, wcs=wcs)
for spine in self._axes.spines.values():
spine.set_zorder(ZORDER_MAX)
self.loading_rectangle = Rectangle((0, 0), 1, 1, color='0.9', alpha=0.9,
zorder=ZORDER_MAX - 1, transform=self.axes.transAxes)
self.loading_rectangle.set_visible(False)
self.axes.add_patch(self.loading_rectangle)
self.loading_text = self.axes.text(0.4, 0.5, 'Computing', color='k',
zorder=self.loading_rectangle.get_zorder() + 1,
ha='left', va='center',
transform=self.axes.transAxes)
self.loading_text.set_visible(False)
self.state.add_callback('aspect', self.update_aspect)
self.update_aspect()
self.state.add_callback('x_min', self.limits_to_mpl)
self.state.add_callback('x_max', self.limits_to_mpl)
self.state.add_callback('y_min', self.limits_to_mpl)
self.state.add_callback('y_max', self.limits_to_mpl)
self.limits_to_mpl()
self.state.add_callback('x_log', self.update_x_log, priority=1000)
self.state.add_callback('y_log', self.update_y_log, priority=1000)
self.update_x_log()
self.axes.callbacks.connect('xlim_changed', self.limits_from_mpl)
self.axes.callbacks.connect('ylim_changed', self.limits_from_mpl)
self.axes.set_autoscale_on(False)
self.state.add_callback('x_axislabel', self.update_x_axislabel)
self.state.add_callback('x_axislabel_weight', self.update_x_axislabel)
self.state.add_callback('x_axislabel_size', self.update_x_axislabel)
self.state.add_callback('y_axislabel', self.update_y_axislabel)
self.state.add_callback('y_axislabel_weight', self.update_y_axislabel)
self.state.add_callback('y_axislabel_size', self.update_y_axislabel)
self.state.add_callback('x_ticklabel_size', self.update_x_ticklabel)
self.state.add_callback('y_ticklabel_size', self.update_y_ticklabel)
self.update_x_axislabel()
self.update_y_axislabel()
self.update_x_ticklabel()
self.update_y_ticklabel()
self.central_widget.resize(600, 400)
self.resize(self.central_widget.size())
self._monitor_computation = QTimer()
self._monitor_computation.setInterval(500)
self._monitor_computation.timeout.connect(self._update_computation)
def _update_computation(self, message=None):
# If we get a ComputationStartedMessage and the timer isn't currently
# active, then we start the timer but we then return straight away.
# This is to avoid showing the 'Computing' message straight away in the
# case of reasonably fast operations.
if isinstance(message, ComputationStartedMessage):
if not self._monitor_computation.isActive():
self._monitor_computation.start()
return
for layer_artist in self.layers:
if layer_artist.is_computing:
self.loading_rectangle.set_visible(True)
text = self.loading_text.get_text()
if text.count('.') > 2:
text = 'Computing'
else:
text += '.'
self.loading_text.set_text(text)
self.loading_text.set_visible(True)
self.redraw()
#.........这里部分代码省略.........
示例14: MatplotlibViewerMixin
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
class MatplotlibViewerMixin(object):
def setup_callbacks(self):
for spine in self.axes.spines.values():
spine.set_zorder(ZORDER_MAX)
self.loading_rectangle = Rectangle((0, 0), 1, 1, color='0.9', alpha=0.9,
zorder=ZORDER_MAX - 1, transform=self.axes.transAxes)
self.loading_rectangle.set_visible(False)
self.axes.add_patch(self.loading_rectangle)
self.loading_text = self.axes.text(0.4, 0.5, 'Computing', color='k',
zorder=self.loading_rectangle.get_zorder() + 1,
ha='left', va='center',
transform=self.axes.transAxes)
self.loading_text.set_visible(False)
self.state.add_callback('x_min', self.limits_to_mpl)
self.state.add_callback('x_max', self.limits_to_mpl)
self.state.add_callback('y_min', self.limits_to_mpl)
self.state.add_callback('y_max', self.limits_to_mpl)
if (self.state.x_min or self.state.x_max or self.state.y_min or self.state.y_max) is None:
self.limits_from_mpl()
else:
self.limits_to_mpl()
self.state.add_callback('x_log', self.update_x_log, priority=1000)
self.state.add_callback('y_log', self.update_y_log, priority=1000)
self.update_x_log()
self.axes.callbacks.connect('xlim_changed', self.limits_from_mpl)
self.axes.callbacks.connect('ylim_changed', self.limits_from_mpl)
self.figure.canvas.mpl_connect('resize_event', self._on_resize)
self._on_resize()
self.axes.set_autoscale_on(False)
self.state.add_callback('x_axislabel', self.update_x_axislabel)
self.state.add_callback('x_axislabel_weight', self.update_x_axislabel)
self.state.add_callback('x_axislabel_size', self.update_x_axislabel)
self.state.add_callback('y_axislabel', self.update_y_axislabel)
self.state.add_callback('y_axislabel_weight', self.update_y_axislabel)
self.state.add_callback('y_axislabel_size', self.update_y_axislabel)
self.state.add_callback('x_ticklabel_size', self.update_x_ticklabel)
self.state.add_callback('y_ticklabel_size', self.update_y_ticklabel)
self.update_x_axislabel()
self.update_y_axislabel()
self.update_x_ticklabel()
self.update_y_ticklabel()
def _update_computation(self, message=None):
pass
def update_x_axislabel(self, *event):
self.axes.set_xlabel(self.state.x_axislabel,
weight=self.state.x_axislabel_weight,
size=self.state.x_axislabel_size)
self.redraw()
def update_y_axislabel(self, *event):
self.axes.set_ylabel(self.state.y_axislabel,
weight=self.state.y_axislabel_weight,
size=self.state.y_axislabel_size)
self.redraw()
def update_x_ticklabel(self, *event):
self.axes.tick_params(axis='x', labelsize=self.state.x_ticklabel_size)
self.axes.xaxis.get_offset_text().set_fontsize(self.state.x_ticklabel_size)
self.redraw()
def update_y_ticklabel(self, *event):
self.axes.tick_params(axis='y', labelsize=self.state.y_ticklabel_size)
self.axes.yaxis.get_offset_text().set_fontsize(self.state.y_ticklabel_size)
self.redraw()
def redraw(self):
self.figure.canvas.draw_idle()
def update_x_log(self, *args):
self.axes.set_xscale('log' if self.state.x_log else 'linear')
self.redraw()
def update_y_log(self, *args):
self.axes.set_yscale('log' if self.state.y_log else 'linear')
self.redraw()
def limits_from_mpl(self, *args, **kwargs):
if getattr(self, '_skip_limits_from_mpl', False):
return
if isinstance(self.state.x_min, np.datetime64):
x_min, x_max = [mpl_to_datetime64(x) for x in self.axes.get_xlim()]
#.........这里部分代码省略.........
示例15: MplRectangularROI
# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_visible [as 别名]
class MplRectangularROI(AbstractMplRoi):
"""
A subclass of RectangularROI that also renders the ROI to a plot
*Attributes*:
plot_opts:
Dictionary instance
A dictionary of plot keywords that are passed to
the patch representing the ROI. These control
the visual properties of the ROI
"""
def __init__(self, axes):
"""
:param axes: A matplotlib Axes object to attach the graphical ROI to
"""
AbstractMplRoi.__init__(self, axes)
self._xi = None
self._yi = None
self.plot_opts = {'edgecolor': PATCH_COLOR, 'facecolor': PATCH_COLOR,
'alpha': 0.3}
self._patch = Rectangle((0., 0.), 1., 1.)
self._patch.set_zorder(100)
self._setup_patch()
def _setup_patch(self):
self._axes.add_patch(self._patch)
self._patch.set_visible(False)
self._sync_patch()
def _roi_factory(self):
return RectangularROI()
def start_selection(self, event):
if event.inaxes != self._axes:
return False
if event.key == SCRUBBING_KEY:
if not self._roi.defined():
return False
elif not self._roi.contains(event.xdata, event.ydata):
return False
self._roi_store()
self._xi = event.xdata
self._yi = event.ydata
if event.key == SCRUBBING_KEY:
self._scrubbing = True
self._cx, self._cy = self._roi.center()
else:
self.reset()
self._roi.update_limits(event.xdata, event.ydata,
event.xdata, event.ydata)
self._mid_selection = True
self._sync_patch()
def update_selection(self, event):
if not self._mid_selection or event.inaxes != self._axes:
return False
if event.key == SCRUBBING_KEY:
if not self._roi.defined():
return False
if self._scrubbing:
self._roi.move_to(self._cx + event.xdata - self._xi,
self._cy + event.ydata - self._yi)
else:
self._roi.update_limits(min(event.xdata, self._xi),
min(event.ydata, self._yi),
max(event.xdata, self._xi),
max(event.ydata, self._yi))
self._sync_patch()
def finalize_selection(self, event):
self._scrubbing = False
self._mid_selection = False
self._patch.set_visible(False)
self._draw()
def _sync_patch(self):
if self._roi.defined():
corner = self._roi.corner()
width = self._roi.width()
height = self._roi.height()
self._patch.set_xy(corner)
self._patch.set_width(width)
self._patch.set_height(height)
#.........这里部分代码省略.........