def __init__(self, ax, data, fs_list, plkwargs, max_collection=500): if pyfusion.VERBOSE > 2: print("init, fs_list size=%d" % (len(fs_list))) self.axes = ax self.canvas = ax.figure.canvas self.data = data self.fs_list = fs_list self.plkwargs = plkwargs self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure # here we define the polygons that indicate that a point is registered # - use empty triangles for simplicity and speed # skip altogether if there are too many # not sure how much this saves - each point still is a datum if (self.Nxy < max_collection): self.collection = RegularPolyCollection(3, 0, sizes=(100, ), facecolors='', edgecolors=facecolors, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) else: self.collection = None self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) print("connected cid=%d" % (self.cid)) self.ind = None
def __init__(self, ax, data, labels=None, color_on='r', color_off='k'): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.call_list = [] self.Nxy = data.shape[0] self.color_on = colorConverter.to_rgba(color_on) self.color_off = colorConverter.to_rgba(color_off) facecolors = [self.color_on for _ in range(self.Nxy)] fig = ax.figure self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(1, ), facecolors=facecolors, edgecolors=facecolors, offsets=self.data, transOffset=ax.transData) ax.add_collection(self.collection, autolim=True) ax.autoscale_view() if labels is not None: ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None self.canvas.draw()
def add_squares(treeplot, nodes, colors='r', size=15, xoff=0, yoff=0, alpha=1.0, vis=True): """ Draw a square at given node Args: p: A node or list of nodes or string or list of strings colors: Str or list of strs. Colors of squares to be drawn. Optional, defaults to 'r' (red) size (float): Size of the squares. Optional, defaults to 15 xoff, yoff (float): Offset for x and y dimensions. Optional, defaults to 0. alpha (float): between 0 and 1. Alpha transparency of squares. Optional, defaults to 1 (fully opaque) zorder (int): The drawing order. Higher numbers appear on top of lower numbers. Optional, defaults to 1000. """ points = xy(treeplot, nodes) trans = offset_copy( treeplot.transData, fig=treeplot.figure, x=xoff, y=yoff, units='points') col = RegularPolyCollection( numsides=4, rotation=pi*0.25, sizes=(size*size,), offsets=points, facecolors=colors, transOffset=trans, edgecolors='none', alpha=alpha, zorder=1 ) col.set_visible(vis) treeplot.add_collection(col) treeplot.figure.canvas.draw_idle()
def __init__(self, df, ax=None, xcol='x', ycol='y', callback=None): self.df = df self.ax = ax or pl.gca() self.canvas = ax.figure.canvas self.lasso_lock = False # indicates if another widget event has priority self.idxs = array(list( self.df.T)) # look up parallel with point indices self.xys = df[[xcol, ycol]].values self.xcol = xcol self.ycol = ycol # timv: don't think this PolyCollection is needed.. self.collection = RegularPolyCollection( numsides=ax.figure.dpi, rotation=6, sizes=(100, ), facecolors=[to_rgba('green', alpha=0.0)] * len(self.xys), linewidths=0, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.user_callback = callback self.canvas.mpl_connect('key_press_event', self.onpress) self.canvas.mpl_connect('button_press_event', self.onpress) self.canvas.mpl_connect('button_release_event', self.onrelease) self.selected = None self.lasso = None
class LassoManager: def __init__(self, ax, data,labels=None, color_on='r', color_off='k'): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.call_list = [] self.Nxy = data.shape[0] self.color_on = colorConverter.to_rgba(color_on) self.color_off = colorConverter.to_rgba(color_off) facecolors = [self.color_on for _ in range(self.Nxy)] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(1,), facecolors=facecolors, edgecolors=facecolors, offsets = self.data, transOffset = ax.transData) ax.add_collection(self.collection, autolim=True) ax.autoscale_view() if labels is not None: ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None self.canvas.draw() def register(self, callback_func): self.call_list.append(callback_func) def callback(self, verts): facecolors = self.collection.get_facecolors() edgecolors = self.collection.get_edgecolors() ind = nonzero(points_inside_poly(self.data, verts))[0] for i in range(self.Nxy): if i in ind: facecolors[i] = self.color_on edgecolors[i] = self.color_on else: facecolors[i] = self.color_off edgecolors[i] = self.color_off self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso self.ind = ind for func in self.call_list: func(ind) def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
def plot_u_matrix(hexagon_offsets, hexagon_color_matrix, hex_side): dpi = 72.0 width = 30 x, y = umatrix_dim xinch = x * width / dpi yinch = y * width / dpi fig = plt.figure(figsize=(xinch, yinch), dpi=dpi) ax = fig.add_subplot(111, aspect='equal') _, _, hex_area = hexagon_dims(hex_side) collection_bg = RegularPolyCollection( numsides=6, # a hexagon rotation=0, sizes=(hex_area,), edgecolors = None, array = hexagon_color_matrix, cmap = cm.Greys, offsets = hexagon_offsets, transOffset = ax.transData, ) ax.add_collection(collection_bg, autolim=True) ax.axis('off') ax.autoscale_view() plt.colorbar(collection_bg) return ax
def update_plot(): #print("update_plot", done) global m, collection, points for p in points: p.remove() del p points = [] x, y = m(lons, lats) points.extend(m.plot(x, y, 'bo')) for name, xpt, ypt in zip(cities, x, y): points.append(mpx.text(xpt + 50000, ypt + 50000, name)) if collection: collection.remove() del collection collection = None collection = ringx.add_collection( RegularPolyCollection(int(fig.dpi), 6, sizes=(10, ), facecolors=colors, offsets=xys, transOffset=ringx.transData)) infos[0].set_text("{} different IPv4s".format(len(nodes_ip4s))) infos[1].set_text("{} different IPv6s".format(len(nodes_ip6s)))
def __init__(self, ax, data,labels=None, color_on='r', color_off='k'): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.call_list = [] self.Nxy = data.shape[0] self.color_on = colorConverter.to_rgba(color_on) self.color_off = colorConverter.to_rgba(color_off) facecolors = [self.color_on for _ in range(self.Nxy)] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(1,), facecolors=facecolors, edgecolors=facecolors, offsets = self.data, transOffset = ax.transData) ax.add_collection(self.collection, autolim=True) ax.autoscale_view() if labels is not None: ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None self.canvas.draw()
def __init__(self, ax, data, fs_list, plkwargs, max_collection=500): if pyfusion.VERBOSE>2: print("init, fs_list size=%d" % (len(fs_list))) self.axes = ax self.canvas = ax.figure.canvas self.data = data self.fs_list = fs_list self.plkwargs = plkwargs self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure # here we define the polygons that indicate that a point is registered # - use empty triangles for simplicity and speed # skip altogether if there are too many # not sure how much this saves - each point still is a datum if (self.Nxy<max_collection): self.collection = RegularPolyCollection( 3, 0, sizes=(100,),facecolors='', edgecolors=facecolors, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) else: self.collection = None self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) print("connected cid=%d" % (self.cid) ) self.ind = None
def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data #the lasso lock boolean is used to tell whether another #widget event has priority self.lassoLock = False self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(100,), facecolors=facecolors, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.cidRelease = self.canvas.mpl_connect('button_release_event', self.onrelease) self.ind = None
class LassoManager: def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(100,), facecolors=facecolors, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None def callback(self, verts): facecolors = self.collection.get_facecolors() ind = nonzero(points_inside_poly(self.xys, verts))[0] for i in range(self.Nxy): if i in ind: facecolors[i] = Datum.colorin else: facecolors[i] = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso self.ind = ind def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) self.canvas.widgetlock(self.lasso)
def __init__(self, df, ax=None, xcol='x', ycol='y', callback=None): self.df = df self.ax = ax or pl.gca() self.canvas = ax.figure.canvas self.lasso_lock = False # indicates if another widget event has priority self.idxs = array(list(self.df.T)) # look up parallel with point indices self.xys = df[[xcol, ycol]].values self.xcol = xcol self.ycol = ycol # timv: don't think this PolyCollection is needed.. self.collection = RegularPolyCollection(numsides=ax.figure.dpi, rotation=6, sizes=(100,), facecolors = [to_rgba('green', alpha=0.0)]*len(self.xys), linewidths = 0, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) self.user_callback = callback self.canvas.mpl_connect('key_press_event', self.onpress) self.canvas.mpl_connect('button_press_event', self.onpress) self.canvas.mpl_connect('button_release_event', self.onrelease) self.selected = None self.lasso = None
class LassoManager: def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data #the lasso lock boolean is used to tell whether another #widget event has priority self.lassoLock = False self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(100,), facecolors=facecolors, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.cidRelease = self.canvas.mpl_connect('button_release_event', self.onrelease) self.ind = None def callback(self, verts): facecolors = self.collection.get_facecolors() ind = nonzero(points_inside_poly(self.xys, verts))[0] for i in range(self.Nxy): if i in ind: facecolors[i] = Datum.colorin else: facecolors[i] = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) #del self.lasso self.ind = ind def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso) # establish boolean that can be used to release the widgetlock self.lassoLock = True def onrelease(self, event): 'on release we reset the press data' # test whether the widgetlock was initiated by the lasso if self.lassoLock: self.canvas.widgetlock.release(self.lasso) self.lassoLock = False print self.ind
def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] self.collection = RegularPolyCollection( 6, sizes=(100,), facecolors=facecolors, offsets=self.xys, offset_transform=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.on_press)
def build_collection(self): self.point_size = self.sl_x2_pointsize.GetValue( ) + 50 # range 50 to 300 self.collection = RegularPolyCollection( #self.axes.figure.dpi, numsides=80, sizes=(self.point_size, ), facecolors=self.color_array, offsets=self.data_array, transOffset=self.axes.transData) self.collection.set_alpha(0.7) self.axes.add_collection(self.collection) #self.axes.axis([self.xmin, self.xmax, self.ymin, self.ymax]) self.axes.autoscale_view() x = self.axes.get_xaxis() y = self.axes.get_yaxis() x.zoom(-1) y.zoom(-1)
def plotAllFlags(): fig, ax = subplots(figsize=(16, 8)) offsets = getOffsets() start = 22 numFlags = [(flags[allChannels][:, -1] & (1 << start)) >> start] cmax = np.max(numFlags[0]) cmin = np.min(numFlags[0]) cmap = get_cmap('jet', cmax - cmin + 1) collection = RegularPolyCollection(numsides=4, rotation=np.pi / 4, sizes=(1000, ), linewidths=(1, ), offsets=offsets, transOffset=ax.transData, alpha=0.5, cmap=cmap) collection.set_clim(vmin=cmin - 0.5, vmax=cmax + 0.5) for i, w in enumerate(range(91) + range(91)): ax.annotate(str(w + 1), offsets[i], ha='center', va='center') subplots_adjust(left=0.2) ax.add_collection(collection) axis('equal') collection.set_array(numFlags[0]) cb = colorbar(collection, ticks=np.arange(cmin, cmax + 1)) rax = axes([0.05, 0.1, 0.1, 0.8]) status = [True, False, False] check = CheckButtons(rax, ('22', '23', '24'), tuple(status)) def func(label): bit = int(label) i = bit - start status[i] = not status[i] if status[i]: numFlags[0] += (flags[allChannels][:, -1] & (1 << bit)) >> bit else: numFlags[0] -= (flags[allChannels][:, -1] & (1 << bit)) >> bit cmax = np.max(numFlags[0]) cmin = np.min(numFlags[0]) cmap = get_cmap('jet', cmax - cmin + 1) ax.collections[0].set_array(numFlags[0]) ax.collections[0].set_clim(vmin=cmin - 0.5, vmax=cmax + 0.5) ax.collections[0].set_cmap(cmap) cb.set_ticks(np.arange(cmin, cmax + 1)) fig.canvas.draw() check.on_clicked(func) show()
class LassoManager(object): def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] # print facecolors self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(20, ), facecolors=facecolors, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) def callback(self, verts): facecolors = self.collection.get_facecolors() p = path.Path(verts) ind = p.contains_points(self.xys) for i in range(len(self.xys)): if ind[i]: facecolors[i] = Datum.colorin self.data[i].color = Datum.colorin else: facecolors[i] = Datum.colorout self.data[i].color = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) # print facecolors del self.lasso def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
def __init__(self, fig, ax, data): self.fig = fig self.axes = ax self.canvas = ax.figure.canvas # 画布 self.data = data self.Nxy = len(data) # 数据长度 self.facecolors = [d.color for d in data] # 所有点的颜色 self.xys = [(d.y, d.x) for d in data] # 所有点的坐标 self.collection = RegularPolyCollection( # 多边形集 4, sizes=(10, ), # 4边形,大小 facecolors=self.facecolors, # 颜色 offsets=self.xys, # 位置 transOffset=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect( 'button_press_event', self.MousePress) # 事件连接,鼠标按键触发MousePress函数 self.cid = self.canvas.mpl_connect( 'key_press_event', self.KeyboardPress) # 事件连接,按键按下触发key_press_event self.KeyFun = '+' # 当前按键功能 '+':添加点,'-':删除点 ax.set_xlabel('+') # 默认添加点
def update_plot(): global done, m, collection, not_found, points for p in points: p.remove() del p points = [] lats = [] lons = [] cities = [] colors = [] not_found.clear() ip4s, ip6s = generate_set() ares = [] for addr, n in ip4s: ares.append((addr, n[0].getNode(), n[2])) for addr, n in ip6s: ares.append((addr, n[0].getNode(), n[2])) for r in ares: res = r[2] n = r[1] if res: lats.append(res['latitude']) lons.append(res['longitude']) cities.append(res['city'] if res['city'] else ( str(int(res['latitude'])) + '-' + str(int(res['longitude'])))) colors.append('red' if n.isExpired() else 'blue') else: not_found.append(r[0]) x, y = m(lons, lats) points.extend(m.plot(x, y, 'bo')) for name, xpt, ypt in zip(cities, x, y): points.append(mpx.text(xpt + 50000, ypt + 50000, name)) node_val = [n.getId().toFloat() for n in all_nodes] xys = [(cos(d * 2 * pi), sin(d * 2 * pi)) for d in node_val] if collection: collection.remove() del collection collection = None collection = ringx.add_collection( RegularPolyCollection(fig.dpi, 6, sizes=(10, ), facecolors=colors, offsets=xys, transOffset=ringx.transData)) node_ip4s, node_ip6s = generate_set() infos[0].set_text("{} different IPv4s".format(len(node_ip4s))) infos[1].set_text("{} different IPv6s".format(len(node_ip6s)))
def __init__(self): self.mode = 'src' # Lists to store the vertices of the source, sky background and # exclusion-zone polygons self.offsets_src = [] self.offsets_sky = [] self.offsets_exc = [] self.offsets = [] # general working array self.apertures = [] # completed polygons for plotting self.measurements = {} # Working polygon collection (points plotted as small polys) self.points = RegularPolyCollection( 10, rotation=0, sizes=(50,), facecolors = 'white', edgecolors = 'black', linewidths = (1,), offsets = self.offsets, transOffset = axplot.transData )
class LassoManager(object): def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] self.collection = RegularPolyCollection(6, sizes=(10, ), facecolors=facecolors, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) def callback(self, verts): facecolors = self.collection.get_facecolors() p = path.Path(verts) ind = p.contains_points(self.xys) for i in range(len(self.xys)): if ind[i]: facecolors[i] = Datum.colorin target = open('badcadences.txt', 'a') target.write('{}, {}'.format(self.xys[i][0], self.xys[i][1])) target.write("\n") target.close() # else: # facecolors[i] = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(100,), facecolors=facecolors, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None
def squares(plot, points, colors, size=15, xoff=0, yoff=0): trans = offset_copy(plot.transData, fig=plot.figure, x=xoff, y=yoff, units='points') col = RegularPolyCollection(numsides=4, rotation=pi * 0.25, sizes=(size * size, ), offsets=points, facecolors=colors, transOffset=trans, edgecolors='none') return plot.add_collection(col)
class LassoManager(object): def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(100,), facecolors=facecolors, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) def callback(self, verts): facecolors = self.collection.get_facecolors() p = path.Path(verts) ind = p.contains_points(self.xys) for i in range(len(self.xys)): if ind[i]: facecolors[i] = Datum.colorin else: facecolors[i] = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
def build_collection(self): self.point_size = self.sl_x2_pointsize.GetValue() + 50 # range 50 to 300 self.collection = RegularPolyCollection( #self.axes.figure.dpi, numsides = 80, sizes=(self.point_size,), facecolors=self.color_array, offsets = self.data_array, transOffset = self.axes.transData) self.collection.set_alpha(0.7) self.axes.add_collection(self.collection) #self.axes.axis([self.xmin, self.xmax, self.ymin, self.ymax]) self.axes.autoscale_view() x = self.axes.get_xaxis() y = self.axes.get_yaxis() x.zoom(-1) y.zoom(-1)
class LassoManager: def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(100, ), facecolors=facecolors, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None def callback(self, verts): facecolors = self.collection.get_facecolors() ind = nonzero(points_inside_poly(self.xys, verts))[0] for i in range(self.Nxy): if i in ind: facecolors[i] = Datum.colorin else: facecolors[i] = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso self.ind = ind def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
def plot_squares(data, name="wq", leg=''): """Function for plotting matrices with squares""" from matplotlib import rc rc('text', usetex=True) plt.rcParams['font.family'] = 'serif' plt.rcParams['font.size'] = 18 factor = 20 pow_factor = 0.6 M = np.array((data))**(pow_factor) * factor M[M > 80] = 80 fig, ax = plt.subplots(1, 1, subplot_kw={'aspect': 'equal'}) ax.set_xlim(-0.5, M.shape[0] - 0.5) ax.set_ylim(-0.5, M.shape[1] - 0.5) # xy locations of each square center xy = np.indices(M.shape)[::-1].reshape(2, -1).T w = (M.ravel()) ec = RegularPolyCollection(4, sizes=w, rotation=pi / 4, facecolor='black', edgecolor='black', offsets=xy, transOffset=ax.transData, norm=10) ax.add_collection(ec) ax.set_xticks(np.arange(0, 28, 4)) ax.set_xticklabels(np.arange(0, 1201, 200)) ax.set_yticks(np.arange(0, 28, 4)) ax.set_yticklabels(np.arange(0, 1201, 200)) ax.set_xlabel("q [MeV]") ax.set_ylabel("$\\omega$ [MeV]") plt.legend((leg, ), loc=2, markerscale=.9) fig.savefig("plots/" + name + ".pdf", dpi=300, bbox_inches='tight', pad_inches=0.1, quality=95) plt.show()
def hexplot( ax: plt.Axes, grid: np.ndarray, data: np.ndarray, hex_size: float=11.5, cmap: str='viridis' ) -> plt.Axes: ''' Plot grid and data on a hexagon grid. Useful for SOMs. Parameters ---------- ax : Axes to plot on. grid : Array of (x, y) tuples. data : Array of len(grid) with datapoint. hex_size : Radius in points determining the hexagon size. cmap : Colormap to use for colouring. Returns ------- ax : Axes with hexagon plot. ''' # Create hexagons collection = RegularPolyCollection( numsides=6, sizes=(2 * np.pi * hex_size ** 2,), edgecolors=(0, 0, 0, 0), transOffset=ax.transData, offsets=grid, array=data, cmap=plt.get_cmap(cmap) ) # Scale the plot properly ax.add_collection(collection, autolim=True) ax.set_xlim(grid[:, 0].min() - 0.75, grid[:, 0].max() + 0.75) ax.set_ylim(grid[:, 1].min() - 0.75, grid[:, 1].max() + 0.75) ax.axis('off') return ax
def __init__(self, axes, useblit=False): self.axes = list(axes) self.canvas = axes[0].figure.canvas self.canvas.mpl_connect('motion_notify_event', self.onmove) self.canvas.mpl_connect('draw_event', self.clear) self.visible = True self.useblit = useblit self.loc = [(0, 0)] self.icons = [] for ax in self.axes: icon = RegularPolyCollection(4, sizes=(75, ), rotation=0.7853981634, facecolors=((0, 0, 0, 0), ), edgecolors=('black', ), offsets=self.loc, transOffset=ax.transData) self.icons.append(icon) ax.add_artist(icon) self.background = None self.needclear = False
class LassoManager: def __init__(self, ax, data, labels=None, color_on='r', color_off='k'): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.call_list = [] self.Nxy = data.shape[0] self.color_on = colorConverter.to_rgba(color_on) self.color_off = colorConverter.to_rgba(color_off) facecolors = [self.color_on for _ in range(self.Nxy)] fig = ax.figure self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(1, ), facecolors=facecolors, edgecolors=facecolors, offsets=self.data, transOffset=ax.transData) ax.add_collection(self.collection, autolim=True) ax.autoscale_view() if labels is not None: ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None self.canvas.draw() def register(self, callback_func): self.call_list.append(callback_func) def callback(self, verts): facecolors = self.collection.get_facecolors() edgecolors = self.collection.get_edgecolors() ind = nonzero(points_inside_poly(self.data, verts))[0] for i in range(self.Nxy): if i in ind: facecolors[i] = self.color_on edgecolors[i] = self.color_on else: facecolors[i] = self.color_off edgecolors[i] = self.color_off self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso self.ind = ind for func in self.call_list: func(ind) def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
from matplotlib.pyplot import figure, show from numpy.random import rand fig = figure() ax = fig.add_subplot(111, xlim=(0, 1), ylim=(0, 1), autoscale_on=False) ax.set_title("Press 'a' to add a point, 'd' to delete one") # a single point offsets = [(0.5, 0.5)] facecolors = [cm.jet(0.5)] collection = RegularPolyCollection( #fig.dpi, 5, # a pentagon rotation=0, sizes=(50, ), facecolors=facecolors, edgecolors='black', linewidths=(1, ), offsets=offsets, transOffset=ax.transData, ) ax.add_collection(collection) def onpress(event): """ press 'a' to add a random point from the collection, 'd' to delete one """ if event.key == 'a': x, y = rand(2)
centros[i * n1 + j] = np.array([1. + i, b + b * j]) else: centros[i * n1 + j] = np.array([1. + i + a, b + b * j]) ax = fig.add_subplot(8, 3, 1 + num) if num < 16: ax.set_title(nombres3[num], fontname="serif", fontsize=4, pad=1) else: ax.set_title(nombres3[num], fontname="serif", fontsize=3, pad=0) collection_bg = RegularPolyCollection( numsides=6, # a hexagon sizes=(25, ), edgecolors='black', linewidths=(0.1, ), array=matriz_peso_2, cmap='gist_rainbow', offsets=centros, transOffset=ax.transData, ) ax.add_collection(collection_bg) ax.set_axis_off() #ax.set_xlim([0, 11.5]) #ax.set_ylim([0, 11.5]) ax.axis('equal') #fig.colorbar(res, shrink = 0.7) #fig.savefig('./Resultados_SOM/resultadosSOM-'+str(l_rate)[2:]+'-'+str(+n_iter)+'-'+str(m1)+'x'+str(n1)+'-PANAL') ### FIN Grafico de Panal 27 ###
# ---------------------------------------------------------------------------- n = 10 offsets = np.ones((n, 2)) offsets[:, 0], offsets[:, 1] = np.linspace(1, 10, n), y X, Y = offsets[:, 0], offsets[:, 1] widths, heights = 15 * np.ones(n), 10 * np.ones(n) numsides = 5 rotation = np.pi / 4 sizes = np.linspace(100, 200, n) linewidths = np.linspace(1, 2, n) facecolors = ['%.1f' % c for c in np.linspace(0.25, 0.75, n)] collection = RegularPolyCollection( numsides, rotation, # linewidths = linewidths, sizes=sizes, facecolors=facecolors, edgecolor="black", offsets=offsets, transOffset=ax.transData) ax.add_collection(collection) ax.text(X[0] - 0.25, y + 0.35, "Regular polygon collection", size="small", ha="left", va="baseline") ax.text(X[-1] + 0.25, y + 0.35, "RegularPolyCollection", color="blue",
class LassoBrowser(object): def __init__(self, df, ax=None, xcol='x', ycol='y', callback=None): self.df = df self.ax = ax or pl.gca() self.canvas = ax.figure.canvas self.lasso_lock = False # indicates if another widget event has priority self.idxs = array(list( self.df.T)) # look up parallel with point indices self.xys = df[[xcol, ycol]].values self.xcol = xcol self.ycol = ycol # timv: don't think this PolyCollection is needed.. self.collection = RegularPolyCollection( numsides=ax.figure.dpi, rotation=6, sizes=(100, ), facecolors=[to_rgba('green', alpha=0.0)] * len(self.xys), linewidths=0, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.user_callback = callback self.canvas.mpl_connect('key_press_event', self.onpress) self.canvas.mpl_connect('button_press_event', self.onpress) self.canvas.mpl_connect('button_release_event', self.onrelease) self.selected = None self.lasso = None def lasso_callback(self, verts): if verts is not None and len(verts): [selected] = nonzero(points_inside_poly(self.xys, verts)) else: selected = [] # change face colors inplace facecolors = self.collection.get_facecolors() facecolors[:] = to_rgba('green', alpha=0.0) facecolors[selected] = to_rgba('yellow', alpha=0.6) # convert from point indices to dataframe indices idx = self.idxs[selected] m = self.df.ix[idx] # show selected rows of dataframe if self.user_callback is None: print m else: self.user_callback(m) self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) self.selected = selected def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return if event.key in ('escape', ): self.selected = [] self.lasso_callback([]) return # TODO: implement zoom out as undo. # zoom in to selection if event.key in ('+', '='): selected_rows = self.df.ix[self.selected] xs = selected_rows[self.xcol] ys = selected_rows[self.ycol] self.ax.set_xlim(xs.min(), xs.max()) self.ax.set_ylim(ys.min(), ys.max()) self.canvas.draw() return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.lasso_callback) self.canvas.widgetlock(self.lasso) # acquire lock on lasso widget self.lasso_lock = True # used when we release def onrelease(self, event): 'on release we reset the press data' # test whether the widgetlock was initiated by the lasso if self.lasso_lock: self.canvas.widgetlock.release(self.lasso) self.lasso_lock = False
class LassoManager: def __init__(self, ax, data, fs_list, plkwargs, max_collection=500): if pyfusion.VERBOSE>2: print("init, fs_list size=%d" % (len(fs_list))) self.axes = ax self.canvas = ax.figure.canvas self.data = data self.fs_list = fs_list self.plkwargs = plkwargs self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure # here we define the polygons that indicate that a point is registered # - use empty triangles for simplicity and speed # skip altogether if there are too many # not sure how much this saves - each point still is a datum if (self.Nxy<max_collection): self.collection = RegularPolyCollection( 3, 0, sizes=(100,),facecolors='', edgecolors=facecolors, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) else: self.collection = None self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) print("connected cid=%d" % (self.cid) ) self.ind = None def callback(self, verts): ind = nonzero(points_inside_poly(self.xys, verts))[0] if pyfusion.VERBOSE>2: print len(self.xys) if pyfusion.VERBOSE>0: print("Try to match the following points to %d fs in list:" % (len(self.fs_list))) print [self.xys[i] for i in ind] if self.collection != None: edgecolors = self.collection.get_edgecolors() for i in range(self.Nxy): if i in ind: edgecolors[i] = Datum.colorin else: edgecolors[i] = Datum.colorout print(self) xarr = [xy[0] for xy in self.xys] yarr = [xy[1] for xy in self.xys] fstarr = array(self.fs_list['t_mid']) fsfarr = array(self.fs_list['freq']) if pyfusion.VERBOSE>5: print("xarr = %s, fsfarr = %s, fstarr=%s, ind = %s" % (xarr, fsfarr, fstarr, ind)) for i in ind: match = (abs(xarr[i] - fstarr) + abs(yarr[i] - fsfarr))< 1e-3 matchinds = match.nonzero()[0] if pyfusion.VERBOSE>5: print("matches", matchinds) if len(matchinds)>6: print('only showing first 6...') matchinds = matchinds[0:10] for m in matchinds: #self.fs_list[m].plot(**self.plkwargs) print("shot {0}, time {1} s".format(self.fs_list['shot'][m],self.fs_list['t_mid'][m])) self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso self.ind = ind def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return if pyfusion.VERBOSE>7: print event.xdata # left button is normal - right does lasso - but this seesm to hang - crash? ## if event.button == 1: self.canvas.button_press_event(event) self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
class LassoManager: def __init__(self, ax, data, fs_list, plkwargs, max_collection=500): if pyfusion.VERBOSE > 2: print("init, fs_list size=%d" % (len(fs_list))) self.axes = ax self.canvas = ax.figure.canvas self.data = data self.fs_list = fs_list self.plkwargs = plkwargs self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure # here we define the polygons that indicate that a point is registered # - use empty triangles for simplicity and speed # skip altogether if there are too many # not sure how much this saves - each point still is a datum if (self.Nxy < max_collection): self.collection = RegularPolyCollection(3, 0, sizes=(100, ), facecolors='', edgecolors=facecolors, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) else: self.collection = None self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) print("connected cid=%d" % (self.cid)) self.ind = None def callback(self, verts): path = Path(verts) self.ind = nonzero(path.contains_points(self.xys))[0] if pyfusion.VERBOSE > 2: print len(self.xys) if pyfusion.VERBOSE > 0: print("Try to match the following points to %d fs in list:" % (len(self.fs_list))) print[self.xys[i] for i in ind] if self.collection != None: edgecolors = self.collection.get_edgecolors() for i in range(self.Nxy): if i in ind: edgecolors[i] = Datum.colorin else: edgecolors[i] = Datum.colorout print(self) xarr = [xy[0] for xy in self.xys] yarr = [xy[1] for xy in self.xys] fstarr = array(self.fs_list['t_mid']) fsfarr = array(self.fs_list['freq']) if pyfusion.VERBOSE > 5: print("xarr = %s, fsfarr = %s, fstarr=%s, ind = %s" % (xarr, fsfarr, fstarr, ind)) for i in self.ind: match = (abs(xarr[i] - fstarr) + abs(yarr[i] - fsfarr)) < 1e-3 matchinds = match.nonzero()[0] if pyfusion.VERBOSE > 5: print("matches", matchinds) if len(matchinds) > 6: print('only showing first 6...') matchinds = matchinds[0:10] for m in matchinds: #self.fs_list[m].plot(**self.plkwargs) print("shot {0}, time {1} s".format(self.fs_list['shot'][m], self.fs_list['t_mid'][m])) self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return if pyfusion.VERBOSE > 7: print event.xdata # left button is normal - right does lasso - but this seesm to hang - crash? ## if event.button == 1: self.canvas.button_press_event(event) self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
class LassoBrowser(object): def __init__(self, df, ax=None, xcol='x', ycol='y', callback=None): self.df = df self.ax = ax or pl.gca() self.canvas = ax.figure.canvas self.lasso_lock = False # indicates if another widget event has priority self.idxs = array(list(self.df.T)) # look up parallel with point indices self.xys = df[[xcol, ycol]].values self.xcol = xcol self.ycol = ycol # timv: don't think this PolyCollection is needed.. self.collection = RegularPolyCollection(numsides=ax.figure.dpi, rotation=6, sizes=(100,), facecolors = [to_rgba('green', alpha=0.0)]*len(self.xys), linewidths = 0, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) self.user_callback = callback self.canvas.mpl_connect('key_press_event', self.onpress) self.canvas.mpl_connect('button_press_event', self.onpress) self.canvas.mpl_connect('button_release_event', self.onrelease) self.selected = None self.lasso = None def lasso_callback(self, verts): if verts is not None and len(verts): [selected] = nonzero(points_inside_poly(self.xys, verts)) else: selected = [] # change face colors inplace facecolors = self.collection.get_facecolors() facecolors[:] = to_rgba('green', alpha=0.0) facecolors[selected] = to_rgba('yellow', alpha=0.6) # convert from point indices to dataframe indices idx = self.idxs[selected] m = self.df.ix[idx] # show selected rows of dataframe if self.user_callback is None: print m else: self.user_callback(m) self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) self.selected = selected def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return if event.key in ('escape',): self.selected = [] self.lasso_callback([]) return # TODO: implement zoom out as undo. # zoom in to selection if event.key in ('+', '='): selected_rows = self.df.ix[self.selected] xs = selected_rows[self.xcol] ys = selected_rows[self.ycol] self.ax.set_xlim(xs.min(), xs.max()) self.ax.set_ylim(ys.min(), ys.max()) self.canvas.draw() return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.lasso_callback) self.canvas.widgetlock(self.lasso) # acquire lock on lasso widget self.lasso_lock = True # used when we release def onrelease(self, event): 'on release we reset the press data' # test whether the widgetlock was initiated by the lasso if self.lasso_lock: self.canvas.widgetlock.release(self.lasso) self.lasso_lock = False
def plot_comp(component_matrix, title, ax, map_shape, colormap, lattice="hexa", mode="color"): """ Plots a component into a rectangular or hexagonal lattice. It allows 'color' and 'size' modes, meaning that the data in the component matrix can be represented as colors or as sizes of the elements in the plot :param component_matrix: matrix containing the data which is intended to be ploted. It must be a 2-D matrix (np.array) :param title: title to be assigned to the component (str) :param ax: matplotlib axis to use to plot the component (matplotlib axis) :param map_shape: shape of the codebook matrices (tuple) :param colormap: colormap to use to generate the plots (matplotlib.cm) :param lattice: lattice to be used to plot the components. Allowed lattices are 'rect' and 'hexa', for rectangular and hexagonal grids (str) :param mode: indicates how the data should be represented in the components (str). There are two possibilities: - 'color': the values of the components will be represented as colors in the grid - 'size': the value of the components will be represented as sizes of the elements of the grid. :return: axis of the last component and list of coordinates of the centers (tuple) """ # describe rectangle or hexagon if lattice == "hexa": radius_f = lambda x: x * 2 / 3 rotation = 0 numsides = 6 elif lattice == "rect": radius_f = lambda x: x / np.sqrt(2) rotation = np.pi / 4 numsides = 4 coordinates = LatticeFactory.build(lattice).generate_lattice(*map_shape[:2]) # Sort to draw left-right top-bottom coordinates = coordinates.copy() coordinates = coordinates[:, ::-1] coordinates = coordinates[np.lexsort([-coordinates[:, 0], -coordinates[:, 1]])] coordinates[:, 1] = -coordinates[:, 1] # Get pixel size between two data points xpoints = coordinates[:, 0] ypoints = coordinates[:, 1] ax.scatter(xpoints, ypoints, s=0.0, marker='s') ax.axis([min(xpoints) - 1., max(xpoints) + 1., min(ypoints) - 1., max(ypoints) + 1.]) xy_pixels = ax.transData.transform(np.vstack([xpoints, ypoints]).T) xpix, ypix = xy_pixels.T radius = radius_f(abs(ypix[map_shape[1]] - ypix[0])) area_inner_circle = math.pi * (radius ** 2) if mode == "color": sizes = [area_inner_circle] * component_matrix.shape[0] elif mode == "size": sizes = area_inner_circle * (component_matrix.reshape(-1) / component_matrix.max()) component_matrix = component_matrix * 0 collection_bg = RegularPolyCollection( numsides=numsides, # a hexagon rotation=rotation, sizes=sizes, array=component_matrix, cmap=colormap, offsets=coordinates, transOffset=ax.transData, ) ax.add_collection(collection_bg, autolim=True) ax.axis('off') ax.autoscale_view() ax.set_title(title) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(collection_bg, cax=cax) if mode != "color": cbar.remove() return ax, coordinates
def plot_rect_map(d_matrix, titles=[], colormap=cm.gray, shape=[1, 1], comp_width=5, hex_shrink=1.0, fig=None, colorbar=True): """ Plot hexagon map where each neuron is represented by a hexagon. The hexagon color is given by the distance between the neurons (D-Matrix) Args: - grid: Grid dictionary (keys: centers, x, y ), - d_matrix: array contaning the distances between each neuron - w: width of the map in inches - title: map title Returns the Matplotlib SubAxis instance """ d_matrix = np.flip(d_matrix, axis=0) def create_grid_coordinates(x, y): coordinates = [ x for row in -1 * np.array(list(range(x))) for x in list( zip(np.arange(((row) % 2) * 0, y + ((row) % 2) * 0), [0.8660254 * (row)] * y)) ] return (np.array(list(reversed(coordinates))), x, y) if d_matrix.ndim < 3: d_matrix = np.expand_dims(d_matrix, 2) if len(titles) != d_matrix.shape[2]: titles = [""] * d_matrix.shape[2] n_centers, x, y = create_grid_coordinates(*d_matrix.shape[:2]) # Size of figure in inches if fig is None: xinch, yinch = comp_width * shape[1], comp_width * (x / y) * shape[0] fig = plt.figure(figsize=(xinch, yinch), dpi=72.) for comp, title in zip(range(d_matrix.shape[2]), titles): ax = fig.add_subplot(shape[0], shape[1], comp + 1, aspect='equal') # Get pixel size between two data points xpoints = n_centers[:, 0] ypoints = n_centers[:, 1] ax.scatter(xpoints, ypoints, s=0.0, marker='s') ax.axis([ min(xpoints) - 1., max(xpoints) + 1., min(ypoints) - 1., max(ypoints) + 1. ]) xy_pixels = ax.transData.transform(np.vstack([xpoints, ypoints]).T) xpix, ypix = xy_pixels.T # discover radius and hexagon apothem = hex_shrink * (xpix[1] - xpix[0]) / math.sqrt(3) area_inner_circle = math.pi * (apothem**2) dm = d_matrix[:, :, comp].reshape(np.multiply(*d_matrix.shape[:2])) collection_bg = RegularPolyCollection( numsides=4, # a square rotation=np.pi / 4, sizes=(area_inner_circle, ), array=dm, cmap=colormap, offsets=n_centers, transOffset=ax.transData, ) ax.add_collection(collection_bg, autolim=True) ax.axis('off') ax.autoscale_view() ax.set_title(title) #, fontdict={"fontsize": 3 * comp_width}) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(collection_bg, cax=cax) if not colorbar: cbar.remove() #cbar.ax.tick_params(labelsize=3 * comp_width) return ax, list(reversed(n_centers))
initState = MotionState(0.2, 0.) pundulum = Pundulum(initState, Fd, 0.04) tmp_alpha = 0. tmp_beta = pundulum.dt*Wd/2/math.pi fig = pyplot.figure(figsize=(19,12)) ax = fig.add_subplot(111, xlim=(-4,4), ylim=(-2.5,2.5), autoscale_on=False) ax.set_title(r"$\omega-\theta change$ $with$ $phase$") ax.set_xlabel(r'$\theta(radians)$', fontsize=14) ax.set_ylabel(r'$\omega(radians/s)$', fontsize=14) offsets = [] collection = RegularPolyCollection(3, offsets=offsets, transOffset=ax.transData,) ax.add_collection(collection) def plot_digram(): global pundulum, tmp_alpha pundulum = Pundulum(initState, Fd, 0.04) del offsets[:] tmp_alpha += 1/32. tmp_alpha %= 1 for i in range(500000): state = pundulum.motionState[0] tmp = state.t*Wd/2/math.pi - tmp_alpha if math.fabs(tmp - int(tmp)) <= tmp_beta: offsets.append((state.b, state.w)) collection.set_offsets(offsets) pundulum.getNextState()
def plot_hexa(grid, d_matrix, w=1080, dpi=72., title='SOM Hit map', colmap='jet'): n_centers = grid['centers'] x, y = grid['x'], grid['y'] if (somx < somy): xinch = (x * w / y) / dpi else: xinch = (y * w / y) / dpi yinch = (y * w / x) / dpi fig = plt.figure(figsize=(xinch, yinch), dpi=dpi) ax = fig.add_subplot(111, aspect='equal') xpoints = n_centers[:, 0] ypoints = n_centers[:, 1] ax.scatter(xpoints, ypoints, s=0.0, marker='s') ax.axis([ min(xpoints) - 1., max(xpoints) + 1., max(ypoints) + 1., min(ypoints) - 1. ]) xy_pixels = ax.transData.transform(np.vstack([xpoints, ypoints]).T) xpix, ypix = xy_pixels.T width, height = fig.canvas.get_width_height() ypix = height - ypix apothem = 1.8 * (xpix[1] - xpix[0]) / math.sqrt(3) #.9 area_inner_circle = math.pi * (apothem**2) collection_bg = RegularPolyCollection( numsides=6, rotation=0, sizes=(area_inner_circle, ), edgecolors=(0, 0, 0, 1), array=d_matrix, cmap=colmap, offsets=n_centers, transOffset=ax.transData, ) ax.add_collection(collection_bg, autolim=True) ax.axis('off') ax.autoscale_view() ax.set_title(title) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="10%", pad=0.05) if (colmap == 'jet'): cbar = plt.colorbar(collection_bg, cax=cax) cbar.ax.invert_yaxis() else: colmap2 = colmap bounds = np.linspace(0, clusters, clusters + 1) bounds2 = np.linspace(0.5, clusters + 0.5, clusters + 1.5) norm = mpl.colors.BoundaryNorm(bounds, colmap2.N) cbar = mpl.colorbar.ColorbarBase(cax, cmap=colmap2, norm=norm, spacing='proportional', ticks=bounds2, boundaries=bounds, format='%1i') cbar.ax.invert_yaxis() plt.gca().invert_yaxis() return ax
class LassoManager(object): def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection( 5, 0, sizes=(30, ), facecolors=facecolors, edgecolor=facecolors, offsets=self.xys, transOffset=ax.transData, ) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) def callback(self, verts): global click global the_table global ind facecolors = self.collection.get_facecolors() p = path.Path(verts) ind = p.contains_points(self.xys) for i in range(len(self.xys)): if ind[i]: facecolors[i] = Datum.colorin else: facecolors[i] = Datum.colorout if sum(ind) > 0: if click > 0: the_table.remove() the_table = plt.table(cellText=[[str(c) for c in show_data[i]] for i in range(len(self.xys)) if ind[i]], colWidths=variablelength_select, colLabels=columns, loc='bottom', bbox=[0.1, -0.6, 0.8, .5]) click = 1 else: if click > 0: the_table.remove() click = 0 self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback)
class MainPanel(wx.Dialog): def __init__(self, parent, pathToPlugins=None):#, main_playlist, nb_playlist): if(not pathToPlugins==None): RESFILE = os.path.join(pathToPlugins,'x2') + os.sep + "layout_x2.xml" wx.Dialog.__init__(self, parent, -1, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) self.parent = parent self.nb_playlist = 0 self.main_playlist = self.parent.lc_playlist #self.super_parent = super_parent # XML Resources can be loaded from a file like this: res = xrc.XmlResource(RESFILE) # Now create a panel from the resource data panel = res.LoadPanel(self, "m_pa_x2main") #self.panel = panel #background = 'tulips.jpg' #img = wx.Image(background, wx.BITMAP_TYPE_ANY) #self.buffer = wx.BitmapFromImage(img) #dc = wx.BufferedDC(wx.ClientDC(panel), self.buffer) #self.panel.Bind(wx.EVT_PAINT, self.OnPaint) # control references -------------------- self.pa_x2main = xrc.XRCCTRL(self, 'm_pa_x2main') self.pa_x2_graph = xrc.XRCCTRL(self, 'm_pa_x2_graph') self.lc_x2_plist = xrc.XRCCTRL(self, 'm_lc_x2_plist') self.cl_x2_features = xrc.XRCCTRL(self, 'm_cl_x2_features') self.sl_x2_pointsize = xrc.XRCCTRL(self, 'm_sl_x2_pointsize') self.lc_x2_plist.InsertColumn(0,"Artist") self.lc_x2_plist.InsertColumn(1,"Song") self.lc_x2_plist.SetColumnWidth(0, 100) self.lc_x2_plist.SetColumnWidth(1, 100) self.Bind(wx.EVT_BUTTON, self.OnAutoGenerateX2Playist, id=xrc.XRCID('m_bu_x2_plize')) self.Bind(wx.EVT_BUTTON, self.OnCenterClick, id=xrc.XRCID('m_bu_x2_center')) self.Bind(wx.EVT_SLIDER, self.OnPointSizeClick, id=xrc.XRCID('m_sl_x2_pointsize')) self.Bind(wx.EVT_SPIN, self.OnZoomClick, id=xrc.XRCID('m_sb_x2_zoom')) self.Bind(wx.EVT_SPIN, self.OnPanXClick, id=xrc.XRCID('m_sb_x2_panx')) self.Bind(wx.EVT_SPIN, self.OnPanYClick, id=xrc.XRCID('m_sb_x2_pany')) self.Bind(wx.EVT_CHECKBOX, self.OnXAxisClick, id=xrc.XRCID('m_cb_x2_xlog')) self.Bind(wx.EVT_CHECKBOX, self.OnYAxisClick, id=xrc.XRCID('m_cb_x2_ylog')) self.Bind(wx.EVT_CHECKLISTBOX, self.OnCheckListBox, self.cl_x2_features) self.current_zoom = 0 self.current_panx = 0 self.current_pany = 0 #features array #tag_array = GetTags() self.cl_x2_features.Set(FEATURES_ARRAY) #self.cl_x2_features.AppendItems(tag_array) self.figure = Figure(None, None, (1,1,1), None, 1.0, True, None)#facecolor=0.75, edgecolor='white') #(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=1.0, frameon=True, subplotpars=None) self.MakeScatt([0,1,2,3]) self.build_graph() self.build_collection() self.canvas = FigureCanvas(self.pa_x2_graph, -1, self.figure) self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel) self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown) #self.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.Bind(wx.EVT_RIGHT_UP, self.OnMouseRightUp) self.canvas.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown) #self.canvas.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.canvas.Bind(wx.EVT_RIGHT_UP, self.OnMouseRightUp) # Note that event is a MplEvent #self.canvas.mpl_connect('motion_notify_event', self.OnMouseMotion) #self.canvas.Bind(wx.EVT_ENTER_WINDOW, self.ChangeCursor) #lasso self.mpl = self.canvas.mpl_connect('button_press_event', self.onpress) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.pa_x2main, 1, wx.EXPAND|wx.ALL, 5) self.SetSizer(sizer) self.SetAutoLayout(True) self.Fit() # ----------------------------------------- # ----------------------------------------- def OnPaint(self, evt): dc = wx.BufferedPaintDC(self.panel, self.buffer) def ChangeCursor(self, curtype): self.canvas.SetCursor(wx.StockCursor(curtype)) def OnMouseRightDown(self, evt): self.canvas.mpl_disconnect(self.mpl) self.canvas.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.ChangeCursor(wx.CURSOR_HAND) self.Refresh() self.oldx = evt.GetPosition()[0] self.oldy = evt.GetPosition()[1] #self.wPos = self.ClientToScreen((0,0)) self.CaptureMouse() #print 'right-down' def OnMouseMotion(self, evt): if evt.Dragging() and evt.RightIsDown(): dPos = evt.GetPosition() #evt.GetEventObject().ClientToScreen(evt.GetPosition()) #nPos = (self.wPos.x + (dPos.x - self.ldPos.x), -2) #nPos = (self.wPos.x + (dPos.x - self.ldPos.x), self.wPos.y + (dPos.y - self.ldPos.y)) #print(nPos) #print self.ldPos curx = dPos[0] cury = dPos[1] x = self.axes.get_xaxis() y = self.axes.get_yaxis() if (curx - self.oldx) < -10: x.pan(.5) self.oldx = curx if (curx - self.oldx) > 10: x.pan(-.5) self.oldx = curx if (cury - self.oldy) > 10: y.pan(.5) self.oldy = cury if (cury - self.oldy) < -10: y.pan(-.5) self.oldy = cury self.canvas.draw() def OnMouseRightUp(self, evt): try: self.ReleaseMouse() except wx._core.PyAssertionError: pass self.ChangeCursor(wx.CURSOR_DEFAULT) self.canvas.Unbind(wx.EVT_MOTION) self.Unbind(wx.EVT_MOTION) self.mpl = self.canvas.mpl_connect('button_press_event', self.onpress) def UpdateStatusBar(self, event): if event.inaxes: x, y = event.xdata, event.ydata self.statusBar.SetStatusText(( "x= " + str(x) + " y=" +str(y) ), 0) def OnPointSizeClick(self, event): self.point_size = self.sl_x2_pointsize.GetValue() + 50 # range 50 to 300 self.figure.clear() self.build_graph() self.build_collection() self.canvas.draw() def OnCenterClick(self, event): self.figure.clear() self.build_graph() self.build_collection() self.canvas.draw() def OnZoomClick(self, event=None): x = self.axes.get_xaxis() y = self.axes.get_yaxis() if event.GetPosition() > self.current_zoom: x.zoom(1) y.zoom(1) else: x.zoom(-1) y.zoom(-1) self.current_zoom = event.GetPosition() self.canvas.draw() def OnMouseWheel(self, evt): rotation = evt.GetWheelRotation() x = self.axes.get_xaxis() y = self.axes.get_yaxis() if rotation > 0: x.zoom(1) y.zoom(1) else: x.zoom(-1) y.zoom(-1) self.canvas.draw() # Done handling event #evt.Skip() def OnPanXClick(self, event): x = self.axes.get_xaxis() y = self.axes.get_yaxis() if event.GetPosition() > self.current_panx: x.pan(1) else: x.pan(-1) self.current_panx = event.GetPosition() self.canvas.draw() def OnPanYClick(self, event): x = self.axes.get_xaxis() y = self.axes.get_yaxis() if event.GetPosition() > self.current_pany: y.pan(1) else: y.pan(-1) self.current_pany = event.GetPosition() self.canvas.draw() def OnXAxisClick(self, event): if self.axes.get_xscale() == 'log': self.axes.set_xscale('linear') else: self.axes.set_xscale('log') #self.axes.autoscale_view() #self.canvas.draw_idle() #self.axes.autoscale_view() self.canvas.draw() #self.canvas.Refresh(eraseBackground=False) def OnYAxisClick(self, event): if self.axes.get_yscale() == 'log': self.axes.set_yscale('linear') else: self.axes.set_yscale('log') #self.axes.autoscale_view() self.canvas.draw() # ---------------------------------------------------------- def OnCheckListBox(self, event): index = event.GetSelection() label = self.cl_x2_features.GetString(index) #print label #print index self.cl_x2_features.SetSelection(index) # so that (un)checking also selects (moves the highlight) #print self.cl_x2_features.GetCount() selected_array =[] for x in range(0, self.cl_x2_features.GetCount()): if self.cl_x2_features.IsChecked(x) == True: selected_array.append(x) print selected_array if len(selected_array) >= 1: #print 'fofofofof' self.figure.clear() self.MakeScatt(selected_array) self.build_graph() self.build_collection() self.canvas.draw() # ---------------------------------------------------------- # ---------------------------------------------------------- def MakeScatt(self, selected_array): pre_data_array, self.song_array, self.color_array, use_std = GetResultsArray(selected_array) #print pre_data_array pca1, pca2, pca3 = pca_module.PCA_svd(pre_data_array, use_std) #print self.data_array #print pca1 #self.data = pca1 #print pca2 #grab the first 2 components self.data_array = np.array_split(pca1,[2,],axis=1)[0] #print self.data_array #self.axes.set_xlabel(r'$\Delta_i$', fontsize=20) #self.axes.set_ylabel(r'$\Delta_{i+1}$', fontsize=20) #self.axes.set_title('Volume and percent change') #self.axes.grid(True) ### use zoom instead #self.xmin = self.data1.min()# - (self.data1.max() * 0.1) #self.xmax = self.data1.max()# * 1.1 #self.ymin = self.data2.min()# - (self.data2.max() * 0.1) #self.ymax = self.data2.max()# * 1.1 def build_graph(self): self.axes = self.figure.add_subplot(111, axisbg=(1,1,1)) self.figure.subplots_adjust(left=0, right=1, top=1, bottom=0) #self.axes.frame_on(False) #subplot(111, axisbg='darkslategray') #ax = fig.add_subplot(111) #self.axes.scatter(self.data2, self.data1, c=[0.5,0.5,1.0], s=200, alpha=0.5) def build_collection(self): self.point_size = self.sl_x2_pointsize.GetValue() + 50 # range 50 to 300 self.collection = RegularPolyCollection( #self.axes.figure.dpi, numsides = 80, sizes=(self.point_size,), facecolors=self.color_array, offsets = self.data_array, transOffset = self.axes.transData) self.collection.set_alpha(0.7) self.axes.add_collection(self.collection) #self.axes.axis([self.xmin, self.xmax, self.ymin, self.ymax]) self.axes.autoscale_view() x = self.axes.get_xaxis() y = self.axes.get_yaxis() x.zoom(-1) y.zoom(-1) #self.axes.axis('tight') ##self.axes.axis('off') def callback(self, verts): facecolors = self.collection.get_facecolors() ind = nonzero(points_inside_poly(self.data_array, verts))[0] for i in range(len(self.data_array)): if i in ind: facecolors[i] = (1,1,0,.5) #print facecolors[i] #pass else: facecolors[i] = self.color_array[i] #pass #print facecolors[i] self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso #self.ind = ind self.pass_data(ind) def onpress(self, event): #print event.button if self.canvas.widgetlock.locked(): #print 'foo' self.canvas.widgetlock.release(self.lasso) #return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso) def pass_data(self, ind): #populate parents list control self.lc_x2_plist.DeleteAllItems() for x in ind: self.lc_x2_plist.InsertStringItem(0, self.song_array[x][0]) self.lc_x2_plist.SetStringItem(0, 1, self.song_array[x][1]) #pass def update_data(self): pass #self.figure.clf() #build_graph(self) #self.MakeScatt() #self.build_collection() def OnAutoGenerateX2Playist(self, event): # copy the sifted list to the playlist self.parent.CheckClear() insert_at = self.parent.lc_playlist.GetItemCount() for x in range(self.lc_x2_plist.GetItemCount(), 0, -1): artist = self.lc_x2_plist.GetItem(x-1, 0).GetText() song = self.lc_x2_plist.GetItem(x-1, 1).GetText() self.parent.SetPlaylistItem(insert_at, artist, song, '', '') #save the playlist self.parent.SavePlaylist() # switch tabs self.parent.nb_main.SetSelection(self.nb_playlist)