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 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()
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 squares(plot, p, colors='r', size=15, xoff=0, yoff=0, alpha=1.0, zorder=1000): """ Draw a square at given node Args: plot (Tree): A Tree plot instance p: A node or list of nodes 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(plot, p) 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', alpha=alpha, zorder=zorder ) plot.add_collection(col) plot.figure.canvas.draw_idle()
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 __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 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 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)
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 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 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 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): 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 )
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 __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
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",
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_map(grid, d_matrix, w=1080, dpi=72., title='SOM Hit map'): """ 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 """ n_centers = grid['centers'] x, y = grid['x'], grid['y'] # Size of figure in inches xinch = (x * w / y) / dpi yinch = (y * w / x) / dpi fig = plt.figure(figsize=(xinch, yinch), dpi=dpi) ax = fig.add_subplot(111, aspect='equal') # Get pixel size between to 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 # In matplotlib, 0,0 is the lower left corner, whereas it's usually the # upper right for most image software, so we'll flip the y-coords width, height = fig.canvas.get_width_height() ypix = height - ypix # discover radius and hexagon apothem = .9 * (xpix[1] - xpix[0]) / math.sqrt(3) area_inner_circle = math.pi * (apothem ** 2) collection_bg = RegularPolyCollection( numsides=6, # a hexagon rotation=0, sizes=(area_inner_circle,), edgecolors = (0, 0, 0, 1), array= d_matrix, cmap = cm.viridis, 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) plt.colorbar(collection_bg, cax=cax) return ax
def plot_hex_map(d_matrix, titles=[], cmap=cm.gray, shape=[1, 1], comp_width=5, hex_shrink=1.0, fig=None, colorbar=True, axis=None, msize=None): """ 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 """ """ A quoi sert-il de presenter une matrice correspondant à un tableau de cartes """ # si on n'a pas de reference de figure fournie on la cree if fig is None: # code original potentiellement inapproprie (maintenant) xinch, yinch = comp_width * shape[1], comp_width * (x / y) * shape[0] fig = plt.figure(figsize=(xinch, yinch), dpi=72.) # on cree les subplot requis #print('shape :',shape) ax_ = fig.subplots(shape[0], shape[1]) if isinstance(ax_, np.ndarray) and isinstance(ax_[0], np.ndarray): ax_ = np.array([ax for sax in ax_ for ax in sax]) #print('ax_.shape :',ax_.shape) # on effectue les transformations de d_matrix pour pouvoir poursuivre #d_matrix = np.flip(d_matrix, axis=0) #d_matrix = np.flip(d_matrix, axis=1) #if d_matrix.ndim < 3: # d_matrix = np.expand_dims(d_matrix, 2) # on calcule les positions de centres et la taille des hexagones r = 1 # rayon circonscrit de l'hexagone -> diametre de 2*r r = 1 / 3**.5 #print('msize :',msize) n_centers, x, y, a = coordinates_hexagonalRegulargrid(*msize, r) #print('d_matrix.shape :',d_matrix.shape) #print('shape :',shape) # on boucle sur chacune des dimensions a afficher for comp, title in zip(range(d_matrix.shape[1]), titles): if isinstance(ax_, np.ndarray): ax = ax_[comp] else: ax = ax_ #print('comp :',comp) #print('ax :',ax) #print('type(ax) :',type(ax)) ax.axis('off') ax.set_title(title) #ax.axis('equal') #ax.set_ylim((min(ypoints) - 1., max(ypoints) + 1.)) ax.set_aspect('equal', adjustable='box') ax.axis([ -a, 2 * (y - .5) * a + (y > 1) * a, -(x - 1) * (r + a / 2) - r, r ]) #ax.grid(True) #print('xlim :',ax.get_xlim()) #print('ylim :',ax.get_ylim()) # les valeurs d'interets par neurone d_ = d_matrix[:, comp].squeeze().flatten() #d_ = np.flipud(np.fliplr(d_matrix[:,comp].reshape(msize[1], msize[0],order='C'))) #raise NotImplementedError('A faire.') # pour la couleur des grandeurs d'interet norm = matplotlib.colors.Normalize(vmin=d_.min(), vmax=d_.max()) facecolors = cmap(norm(d_)) # creation de la collection de polygones if False: area_inner_circle = math.pi * (apothem**2 ) # ne correspond pas a sizes collection_bg = RegularPolyCollection( numsides=6, # a hexagon rotation=0, sizes=(area_inner_circle, ), # en points -> pbm facecolors=facecolors, #array=d_, edgecolors=("black", ), cmap=cmap, norm=norm, offsets=n_centers, transOffset=ax.transData, ) else: lesHexagones = [] for i in range(len(n_centers)): lesHexagones.append( RegularPolygon(xy=n_centers[i], numVertices=6, radius=r, orientation=0., facecolor=facecolors[i], edgecolor='k')) collection_bg = PatchCollection(lesHexagones, match_original=True) # et ajout ... ax.add_collection(collection_bg) # on ajoute la colorbar sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) sm.set_array([]) # only needed for matplotlib < 3.1 # colobar horizontale if True: divider = make_axes_locatable(ax) cax = divider.new_vertical(size="5%", pad=0.5, pack_start=True) fig.add_axes(cax) cbar = fig.colorbar(sm, cax=cax, orientation="horizontal") else: cbar = fig.colorbar(sm) if not colorbar: cbar.remove() #cbar.ax.tick_params(labelsize=3 * comp_width) if isinstance(ax_, np.ndarray): for i in range(d_matrix.shape[1], len(ax_)): ax_[i].axis('off') return ax_, list(reversed(n_centers))
def plot_hexa(grid, d_matrix, w=1080, dpi=72., title='SOM Hit map', colmap='jet', ptype='scatter'): 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 # In matplotlib, 0,0 is the lower left corner, whereas it's usually the # upper right for most image software, so we'll flip the y-coords width, height = fig.canvas.get_width_height() ypix = height - ypix # discover radius and hexagon #apothem = 1.8 * (xpix[1] - xpix[0]) / math.sqrt(3)#.9 if(ptype=='scatter'): #if the data type is csv with gaps apothem=(xpix[1] - xpix[0]) area_inner_circle = abs(apothem) collection_bg = RegularPolyCollection( numsides=4, rotation=150, sizes=(area_inner_circle,), edgecolor="none", #edgecolors = (0, 0, 0, 1), array= d_matrix, cmap = colmap, offsets = n_centers, transOffset = ax.transData, ) else: #regular hexa plot apothem = 1.8 * (xpix[1] - xpix[0]) / math.sqrt(3)#.9 oli area_inner_circle = math.pi * (apothem ** 2) collection_bg = RegularPolyCollection( numsides=6, # a hexagon 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="5%", pad=0.05) #plt.colorbar(collection_bg, cax=cax)#cm.ScalarMappable(norm=norm, cmap=cmap) if(colmap=='jet'): cbar=plt.colorbar(collection_bg, cax=cax,ticklocation='right', aspect=10) cbar.ax.invert_yaxis() cbar.ax.tick_params(axis='y', direction='out', pad=30) 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',ticklocation='right', ticks=bounds2, boundaries=bounds, format='%1i') cbar.ax.invert_yaxis() cbar.ax.tick_params(axis='y', direction='out', pad=30) plt.gca().invert_yaxis() return ax
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
#tmp_alpha = [0, 1/8., 1/4., 3/8.] tmp_alpha = [1/2., 5/8., 3/4., 7/8.] tmp_beta = pundulum.dt*Wd/2/math.pi fig = pyplot.figure(figsize=(19,12)) ax = [] ax.append(fig.add_subplot(221, xlim=(-4,4), ylim=(-2.5,2.5), autoscale_on=False)) ax.append(fig.add_subplot(222, xlim=(-4,4), ylim=(-2.5,2.5), autoscale_on=False)) ax.append(fig.add_subplot(223, xlim=(-4,4), ylim=(-2.5,2.5), autoscale_on=False)) ax.append(fig.add_subplot(224, xlim=(-4,4), ylim=(-2.5,2.5), autoscale_on=False)) offsets = [[], [], [], []] collection = [[], [], [], []] for i in range(4): collection[i] = RegularPolyCollection(3, offsets=offsets[i], transOffset=ax[i].transData,) ax[i].add_collection(collection[i]) plot_regular(ax[i], i) def plot_digram(n): global pundulum for i in range(5000): state = pundulum.motionState[0] tmp = state.t*Wd/2/math.pi - tmp_alpha[n] if math.fabs(tmp - int(tmp)) <= tmp_beta: offsets[n].append((state.b, state.w)) collection[n].set_offsets(offsets[n]) pundulum.getNextState() del pundulum.motionState[0] fig.canvas.draw()
def plot_map(d_matrix, pointing, outdir, w=1080, dpi=72., title='SPI hit map'): """ Plot hexagon map where each detector is represented by a hexagon. The hexagon color is given by the number of counts incident on the detector (D-Matrix) Args:, - d_matrix: array contaning the distances between each neuron - w: width of the map in inches - title: map title Returns the Matplotlib SubAxis instance """ # Define the SPI detector grid grid = { 'centers': np.array([[0, 0], [1, 0], [0.5, 1], [-0.5, 1], [-1, 0], [-0.5, -1], [0.5, -1], [1.5, -1], [2, 0], [1.5, 1], [1, 2], [0, 2], [-1, 2], [-1.5, 1], [-2, 0], [-1.5, -1], [-1, -2], [0, -2], [1, -2]]), 'x': np.array([3.]), 'y': np.array([3.]) } n_centers = grid['centers'] x, y = grid['x'], grid['y'] # Size of figure in inches xinch = (x * w / y) / dpi yinch = (y * w / x) / dpi fig = plt.figure(figsize=(xinch, yinch), dpi=dpi) ax = fig.add_subplot(111, aspect='equal') # Get pixel size between to 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 # In matplotlib, 0,0 is the lower left corner, whereas it's usually the # upper right for most image software, so we'll flip the y-coords width, height = fig.canvas.get_width_height() ypix = height - ypix # discover radius and hexagon apothem = .9 * (xpix[1] - xpix[0]) / math.sqrt(3) area_inner_circle = math.pi * (apothem**2) collection_bg = RegularPolyCollection( numsides=6, # a hexagon rotation=0, sizes=(area_inner_circle, ), edgecolors=(0, 0, 0, 1), array=d_matrix, cmap='inferno', offsets=n_centers, transOffset=ax.transData) I = ax.add_collection(collection_bg) I.set_clim(vmin=1000, vmax=1800) 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) plt.colorbar(collection_bg, cax=cax) plt.savefig(outdir + '/' + str(pointing) + '_hitmap.png') return print('Output saved in ' + outdir + '/' + str(pointing) + '_hitmap.png')
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)
def imshow_hexagonal(data: xr.DataArray, *, hlpr: PlotHelper, colormap: Union[str, mpl.colors.Colormap], **kwargs ) -> mpl.image.AxesImage: """Display data as an image, i.e., on a 2D hexagonal grid. Args: data (xr.DataArray): The array-like data to plot as image. hlpr (PlotHelper): The plot helper. colormap (str or mpl.colors.Colormap): The colormap to use. Returns: The RegularPolyCollection representing the hexgrid. """ width, height = _get_ax_size(hlpr.ax, hlpr.fig) s = (height / data.y.size) / 0.75 / 2 # NOTE the 0.75 factor is required because of the hexagonal offset geometry area = 3**1.5 / 2 * s**2 # distinguish pair and impair rows (impair have offset) hex_s = 2 * data.isel(y=0).y y_ids = ((data.y / hex_s - 0.5) / 0.75).round().astype(int) # compute offsets of polygons xx, yy = np.meshgrid(data.x, data.y) x_offsets = xr.DataArray(data=xx, dims=("y", "x"), coords=dict(x=data.x, y=data.y)) y_offsets = xr.DataArray(data=yy, dims=("y", "x"), coords=dict(x=data.x, y=data.y)) # ... and add an x-offset for impair rows x_origin = data.isel(x=0, y=0).coords['x'] x_offsets[y_ids % 2 == 1] += x_origin # # assign the true coordinates # d = d.assign_coords(x=('x', d.x)) # d_offset = d_offset.assign_coords(x=('x', d_offset.x + x_origin)) # get the color mapping if isinstance(colormap, str): cmap = mpl.cm.get_cmap(name=colormap) else: cmap = colormap map_color = mpl.cm.ScalarMappable(cmap=cmap) pcoll = RegularPolyCollection( 6, sizes=(area,), rotation=0, facecolor=map_color.to_rgba(data.data.flatten()), offsets=np.transpose( [x_offsets.data.flatten(), y_offsets.data.flatten()] ), transOffset=hlpr.ax.transData, animated=True, ) hlpr.ax.add_collection(pcoll) # use same length scale in x and y hlpr.ax.set_aspect('equal') # rescale cmap im = mpl.image.AxesImage(hlpr.ax) im.set_cmap(colormap) if 'vmin' in kwargs and 'vmax' in kwargs: # From `limits` argument; will either have none or both im.set_clim(kwargs['vmin'], kwargs['vmax']) return im
for i in range(m_nuevo): for j in range(n_nuevo): if j % 2 == 0: centros[i * n_nuevo + j] = np.array([1. + i, b + b * j]) else: centros[i * n_nuevo + j] = np.array([1. + i + a, b + b * j]) fig = plt.figure(figsize=(3.5, 3.5)) ax = fig.add_subplot(111) collection_bg = RegularPolyCollection( numsides=6, # a hexagon sizes=(35, ), edgecolors='black', linewidths=(0.3, ), array=pesos_3d_a_2d, cmap='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)+'-PANALCLUSTER') plt.savefig("kmeansPlano3d.pdf", bbox_inches='tight')