def __init__(self, ax, snapshot): self.snapshot = snapshot self.ax = ax self.ax.set_aspect("equal", "box-forced") self.grass = BboxImage(ax.bbox, interpolation="bicubic", zorder=-1000) self.ax.add_artist(self.grass) self.grass.set_data(GRASS) for lane in self.snapshot.lanes: path = Path( [ lane.p - LANE_SCALE * lane.m - lane.n * lane.w * 0.5, lane.p - LANE_SCALE * lane.m + lane.n * lane.w * 0.5, lane.q + LANE_SCALE * lane.m + lane.n * lane.w * 0.5, lane.q + LANE_SCALE * lane.m - lane.n * lane.w * 0.5, lane.p - LANE_SCALE * lane.m - lane.n * lane.w * 0.5, ], [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY ], ) ax.add_artist( PathPatch( path, facecolor=LANE_COLOR, lw=0.5, edgecolor=LANE_BCOLOR, zorder=-100, )) self.robots = [ AxesImage(self.ax, interpolation="bicubic", zorder=0) for robot in self.snapshot.robots ] for robot in self.robots: self.ax.add_artist(robot) self.human = AxesImage(self.ax, interpolation="bicubic", zorder=100) self.ax.add_artist(self.human) self.ts = np.linspace(0.0, self.snapshot.human.T, STEPS) xs = self.snapshot.human.ix(self.ts) self.h_future = ax.plot(xs[:, 0], xs[:, 1], zorder=50, linestyle="--", color="white", linewidth=1.0)[0] self.h_past = ax.plot(xs[:, 0], xs[:, 1], zorder=40, linestyle="-", color="blue", linewidth=2.0)[0] self.ax.set_xlim(-0.5, 0.5) self.ax.set_ylim(-0.2, 0.8)
def test_axesimage_setdata(): ax = plt.gca() im = AxesImage(ax) z = np.arange(12, dtype=float).reshape((4, 3)) im.set_data(z) z[0, 0] = 9.9 assert im._A[0, 0] == 0, 'value changed'
def __init__(self, network): self._network = network self._algorithm = MetropolisAlgorithm(network) fig = pyplot.figure() image_axis = fig.add_subplot(131, aspect='equal') self._plots.append(PlotTracker(network, 'energy', fig.add_subplot(132))) self._plots.append( PlotTracker(network, 'polarization', fig.add_subplot(133))) self.image = AxesImage(image_axis, cmap='Greys', interpolation='nearest') image_axis.set_xlim(0, network.cols - 1) image_axis.set_ylim(0, network.rows - 1) image_axis.add_image(self.image) burnAxis = pyplot.axes([0.1, 0.05, 0.8, 0.05]) self.burnSlider = Slider(burnAxis, 'Burn-off', 0, 1, valinit=0, valfmt=u'%d') self.burnoff = 0 self.burnSlider.on_changed(lambda x: self._update_burnoff(x)) animation.TimedAnimation.__init__(self, fig, blit=True)
def setCanvas(self, **kwargs): """Set canvas to plot in :param figure: Matplotlib figure to plot in :type figure: :py:class:`matplotlib.Figure` :param axes: Matplotlib axes to plot in :type axes: :py:class:`matplotlib.Axes` :raises: TypeError """ axes = kwargs.get('axes', None) figure = kwargs.get('figure', None) if isinstance(axes, plt.Axes): self.fig, self.ax = axes.get_figure(), axes self._show_plt = False elif isinstance(figure, plt.Figure): self.fig, self.ax = figure, figure.gca() self._show_plt = False elif axes is None and figure is None and self.fig is None: self.fig, self.ax = plt.subplots(1, 1) self._show_plt = True else: raise TypeError('axes has to be of type matplotlib.Axes. ' 'figure has to be of type matplotlib.Figure') self.image = AxesImage(self.ax) self.ax.add_artist(self.image)
def visualize(traj_real, traj_fake, seq_start_end): st.button('show animation') animation_image = st.empty() fig, ax = plt.subplots() ax.set_xlim(-50, 50) ax.set_ylim(-30, 30) plt.xlabel("Meters") plt.ylabel("Meters") CAR = { color: zoom(plt.imread('/home/ubuntu/CarGAN/img/car-{}.png'.format(color)), [0.3, 0.3, 1.]) for color in ['gray', 'orange', 'purple', 'red', 'white', 'yellow'] } #rect = patches.Rectangle((-50,-35),100,70,linewidth=1,edgecolor='none',facecolor='gray') #ax.add_patch(rect) scale = 5. / max(CAR['gray'].shape[:2]) st.sidebar.subheader('Select a scene to visualize') scene_num = st.sidebar.selectbox('Scene #', range(0, len(seq_start_end)), 1) start, end = seq_start_end[scene_num] num_agents = end - start traj_real = traj_real[:, start:end, :].cpu().detach().numpy( ) #trajectories of all the agents in the scene traj_fake = traj_fake[:, start:end, :].cpu().detach().numpy() color = ['gray', 'orange', 'purple', 'red', 'yellow', 'white'] angle = np.zeros((traj_fake.shape[0], traj_fake.shape[1])) c = 0 for i in range(num_agents): x_pos = traj_fake[:, i, 0] y_pos = traj_fake[:, i, 1] den = x_pos[1:] - x_pos[:-1] num = y_pos[1:] - y_pos[:-1] angle[1:, i] = np.arctan2(num, den) ax.plot(traj_fake[:, i, 0], traj_fake[:, i, 1], lw=0.5, linestyle='--', color=color[c], label="agent#" + str(i)) plt.text(traj_fake[0, i, 0] + 2., traj_fake[0, i, 1] + 2., str(i)) c += 1 angle = angle.reshape((angle.shape[0], angle.shape[1], 1)) x_vec = np.concatenate((traj_fake, angle), axis=2) cars = [ AxesImage(ax, interpolation='bicubic', zorder=100) for _ in np.arange(x_vec.shape[1]) ] for num in range(x_vec.shape[0]): c = 0 for car in cars: ax.add_artist(car) set_image(car, CAR[color[c]], scale, x_vec[num, c, :]) c += 1 animation_image.pyplot(fig) final_scene_num = scene_num st.sidebar.subheader('Select an agent to make adversarial') final_agent_num = st.sidebar.selectbox('Agent #', range(0, end - start), 1) return final_scene_num, final_agent_num
def image(self): if self._image is not None: return self._image px, py, dx, dy = self._corners self._image = AxesImage(self.axes, origin='lower', interpolation='nearest') self._image.set_data(self.im) self._image.set_extent((dx[0], dx[-1], dy[0], dy[-1])) self.axes._set_artist_props(self._image) return self._image
def create_artists(self, legend, artist, xdescent, ydescent, width, height, fontsize, trans): # Obtain the Axes object of this legend ax = legend.axes # Obtain the colormap of the artist cmap = artist.cmap # Create an AxesImage to contain the colormap with proper dimensions image = AxesImage(ax, cmap=cmap, transform=trans, extent=[xdescent, width, ydescent, height]) # Set the data of the image image.set_data(np.arange(cmap.N)[np.newaxis, ...]) # Return the AxesImage object return ([image])
def __init__(self, t, xy, roi, n, *args, **kwargs): self.figure = None self._t = t self._xy = xy # (n,2) array self._roi = roi # [ [xmin, xmax], [ymin, ymax] ] self._n = n # integer # construct artists for current position, future and past paths self._current = Line2D( [], [], marker='o', color='black', linestyle='none', markersize=10, clip_on=True ) self._future = [ Line2D( [], [], marker='.', color='red', linestyle='none', clip_on=True ) for x in range(self._n+1) ] self._past = [ Line2D( [], [], marker='.', color='blue', linestyle='none', clip_on=True ) for x in range(self._n+1) ] # construct artists for background img, _, _ = np.histogram2d( xy[:,0], xy[:,1], bins=[100,100], range=roi, normed=True ) img[img>0.] = 0.2 self._all = [ AxesImage( None, data=img.T, cmap='gray_r', norm=matplotlib.colors.Normalize(vmin=0, vmax=1.) ) for x in range(self._n+1) ] super(PositionTimeStrip, self).__init__(*args, **kwargs)
def _do_init(self) -> Gtk.Widget: from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas from matplotlib.figure import Figure from matplotlib.image import AxesImage self._widget = Gtk.Grid() figure = Figure(tight_layout=True) self._figure_canvas = FigureCanvas(figure) self._figure_canvas.props.hexpand = True self._figure_canvas.props.vexpand = True self._figure_canvas.show() self._widget.add(self._figure_canvas) # Axes self._axes = figure.add_subplot(1, 1, 1) self._axes.set_aspect('equal', 'box') self._axes.xaxis.tick_top() for item in (*self._axes.get_xticklabels(), *self._axes.get_yticklabels()): item.set_fontsize(8) self._axes_bg_image = AxesImage(ax=self._axes) # Placeholder transparent 1x1 image (rgba format) self._axes_bg_image.set_data(np.zeros((1, 1, 4))) self._axes.add_image(self._axes_bg_image) self._profile_extract_line = self._axes.plot([], linestyle='-', color='#0080ff', linewidth=1.5)[0] self._profile_fit_line = self._axes.plot([], linestyle='-', color='#ff0080', linewidth=1)[0] self.presenter.view_ready() return self._widget
def plot_data2D(self, data2D, dataX, dataY, tabs_canvas_index, plot_canvas_index, title="", xtitle="", ytitle="", mode=2): for i in range(1+self.tab[tabs_canvas_index].layout().count()): self.tab[tabs_canvas_index].layout().removeItem(self.tab[tabs_canvas_index].layout().itemAt(i)) if mode == 0: figure = FigureCanvas(gol.plot_image(data2D, dataX, dataY, xtitle=xtitle, ytitle=ytitle, title=title, show=False, aspect='auto')) self.plot_canvas[plot_canvas_index] = figure else: origin = (dataX[0],dataY[0]) scale = (dataX[1]-dataX[0],dataY[1]-dataY[0]) data_to_plot = data2D.T colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256} if mode == 1: #TODO: delete: srio commented this part as it is never used raise Exception("Cannot use XoppyPlot.XoppyImageView()") # self.plot_canvas[plot_canvas_index] = XoppyPlot.XoppyImageView() # colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256} # # self.plot_canvas[plot_canvas_index]._imagePlot.setDefaultColormap(colormap) # self.plot_canvas[plot_canvas_index].setImage(numpy.array(data_to_plot), origin=origin, scale=scale) elif mode == 2: self.plot_canvas[plot_canvas_index] = Plot2D() self.plot_canvas[plot_canvas_index].resetZoom() self.plot_canvas[plot_canvas_index].setXAxisAutoScale(True) self.plot_canvas[plot_canvas_index].setYAxisAutoScale(True) self.plot_canvas[plot_canvas_index].setGraphGrid(False) self.plot_canvas[plot_canvas_index].setKeepDataAspectRatio(True) self.plot_canvas[plot_canvas_index].yAxisInvertedAction.setVisible(False) self.plot_canvas[plot_canvas_index].setXAxisLogarithmic(False) self.plot_canvas[plot_canvas_index].setYAxisLogarithmic(False) #silx 0.4.0 self.plot_canvas[plot_canvas_index].getMaskAction().setVisible(False) self.plot_canvas[plot_canvas_index].getRoiAction().setVisible(False) self.plot_canvas[plot_canvas_index].getColormapAction().setVisible(False) self.plot_canvas[plot_canvas_index].setKeepDataAspectRatio(False) self.plot_canvas[plot_canvas_index].addImage(numpy.array(data_to_plot), legend="zio billy", scale=scale, origin=origin, colormap=colormap, replace=True) self.plot_canvas[plot_canvas_index].setActiveImage("zio billy") # COLOR TABLE from matplotlib.image import AxesImage image = AxesImage(self.plot_canvas[plot_canvas_index]._backend.ax) image.set_data(numpy.array(data_to_plot)) self.plot_canvas[plot_canvas_index]._backend.fig.colorbar(image, ax=self.plot_canvas[plot_canvas_index]._backend.ax) self.plot_canvas[plot_canvas_index].setGraphXLabel(xtitle) self.plot_canvas[plot_canvas_index].setGraphYLabel(ytitle) self.plot_canvas[plot_canvas_index].setGraphTitle(title) self.tab[tabs_canvas_index].layout().addWidget(self.plot_canvas[plot_canvas_index])
def imshow_classification_overlay(ax, _data, pol_suf, xq='theta', yq='wavelength', cmap='custom', repr_measure='silhouettes', make_comparable_to=None, bkg_black=True, exponent=1., clip_zero=0.0, clip_softly=True, overdrive=0., plot_cbar=True, **kwargs): from matplotlib.image import AxesImage from sklearn.preprocessing import minmax_scale data = deepcopy(_data) # The image data based on the cluster labels data_labels = get_pivot_data(data, 'Classification' + pol_suf, xq, yq) image = data_labels.values if repr_measure == 'distances': if not make_comparable_to is None: raise NotImplementedError('`make_comparable_to` ia only ' + 'implemented for `repr_measure="silhouettes"`') # Alpha data based on the Euclidian distances distances = data['Euclidian_Distances' + pol_suf] data['_pl_alpha'] = minmax_scale(1. / distances) data_alpha = get_pivot_data(data, '_pl_alpha', xq, yq) alpha = data_alpha.values elif repr_measure == 'silhouettes': silhouettes = get_pivot_data(data, 'Silhouettes' + pol_suf, xq, yq).values if make_comparable_to is None: _gmin = silhouettes.min() _gmax = silhouettes.max() _ptp = silhouettes.ptp() else: sil_comp = make_comparable_to['Silhouettes' + pol_suf] _min1, _max1 = silhouettes.min(), silhouettes.max() _min2, _max2 = sil_comp.min(), sil_comp.max() _gmax = max([_max1, _max2]) _gmin = min([_min1, _min2]) _ptp = _gmax - _gmin sil_range = (_gmin, _gmax) alpha = (silhouettes - _gmin) / _ptp elif repr_measure == 'probability': alpha = get_pivot_data(data, 'Probability' + pol_suf, xq, yq).values sil_range = (0., 1.) # Manipulate the alphas based on clipping and n_sqrts settings if overdrive > 0.: alpha = np.clip(alpha * (1. + overdrive), 0., 1.) if exponent != 1.: alpha = np.power(alpha, exponent) if clip_zero > 0. and clip_zero < 1.: if clip_softly: alpha = minmax_scale(alpha.ravel(), (clip_zero, 1.)). \ reshape(alpha.shape) else: alpha = np.clip(alpha, clip_zero, 1.) # # Set new maximum # if max_final < 1.: # alpha = minmax_scale(alpha.ravel(), (clip_zero, max_final)).\ # reshape(alpha.shape) if clip_zero >= 1.: alpha = np.ones_like(alpha) extent = (data_labels.columns.min(), data_labels.columns.max(), data_labels.index.min(), data_labels.index.max()) # make a color map of fixed colors n_colors = int(image.max()) + 1 cmap, bounds, norm = get_discrete_cmap(n_colors, cmap) # Set default kwargs kwdefaults = dict(origin='lower', aspect='auto', interpolation='none') for dkey, dval in kwdefaults.iteritems(): if not dkey in kwargs: kwargs[dkey] = dval # get dummy_image for colorbar im_dummy = ax.imshow(image, extent=extent, cmap=cmap, norm=norm, **kwargs) ax.images.pop() # remove it afterwards # Get an AxesImage to convert to RGBA im = AxesImage(ax, cmap, norm, kwdefaults['interpolation'], kwdefaults['origin'], extent) rgba = im.to_rgba(image) # Set the alpha column to the alpha values based on the distance measure rgba[:, :, 3] = alpha # Create a black background image if bkg_black is True if bkg_black: im_black = deepcopy(rgba) im_black[:, :, :3] = 0. im_black[:, :, 3] = 1. im = ax.imshow(im_black, extent=extent, **kwargs) im = ax.imshow(rgba, extent=extent, **kwargs) # Draw the colorbar if plot_cbar: if hasattr(ax, 'cax'): cax = ax.cax else: cax = None cb = plt.colorbar(im_dummy, cmap=cmap, norm=norm, boundaries=bounds, ticks=bounds[1:] - 0.5, cax=cax) cb.set_ticklabels([str(int(it)) for it in bounds[1:]]) # Set labels if hasattr(ax, 'cax') and plot_cbar: ax.cax.set_ylabel('Labels') ax.set_xlabel(xq) ax.set_ylabel(yq) ax.set_title('Clustering of $E$-field data') if repr_measure == 'distances': return im, im_dummy, bounds return im, im_dummy, bounds, sil_range
color_list = [] for shape_dict in m.states_info: cur_name = shape_dict['NAME'] state_names.append(cur_name) # Don't have data-collection for PR, so skip if cur_name == 'Puerto Rico': color_list.append([0, 0, 0, 0]) continue state_count = states[states["name"] == cur_name]["count_by_pop"] cur_color = cmap(norm(state_count))[0] color_list.append(cur_color) ax = plt.gca() # Color each state and render on map for nshape, seg in enumerate(m.states): color = rgb2hex(color_list[nshape]) poly = Polygon(seg, facecolor=color, edgecolor=color) ax.add_patch(poly) plt.title('Number of Tweets per Million Residents\n about COVID-19 per State') # Render the colorbar legend img = AxesImage(states["count_by_pop"], cmap, norm=norm) cb = plt.colorbar(img) print(states[["name", "count", "count_by_pop"]]) plt.savefig('../plots/state_counts_by_pop.png') plt.show()
num = pos_y[1:] - pos_y[:-1] angle[i, 1:] = num / den angle[i, :] = [0. if math.isnan(x) else x for x in angle[i, :]] ax.plot(sc[i, :, 0].cpu().detach().numpy(), sc[i, :, 1].cpu().detach().numpy(), color=color[c], linestyle='--') ax.plot(gt[i, :, 0].cpu().detach().numpy(), gt[i, :, 1].cpu().detach().numpy(), color=color[c]) c += 1 angle = angle.reshape(gt.size(0), gt.size(1), 1) x_vec = np.concatenate( (sc_np[seq_num:seq_num + 4], angle[seq_num:seq_num + 4]), axis=2) t = np.arange(x_vec.shape[1]) t = st.slider('Time', 0, x_vec.shape[1] - 1, 0) cars = [ AxesImage(ax, interpolation='bicubic', zorder=100) for _ in np.arange(x_vec.shape[0]) ] c = 0 for car in cars: ax.add_artist(car) set_image(car, CAR[color[c]], scale, x_vec[c, t, :]) c += 1 plt.ylabel('Meters') plt.xlabel('Meters') ax.set_xlim(-35., 35.) ax.set_ylim(-35., 35.) st.write(fig)