def define(self): self.con = ConnectionPatch(lw=1.5, color=(.25, .25, 1), picker=10, xyA=(self.x0, self.y0), coordsA='data', axesA=self.ax0, xyB=(self.xx, self.yy), coordsB='data', axesB=self.axx) self.con.parent = self super(BlitFigure, self.master).add_artist(self.con) self.master.add_artist(self.con) self.scat += [ self.axx.scatter(self.xx, self.yy, c=[], s=200, linewidth=1.5, edgecolors=(.25, .25, 1)) ] self.master.add_artist(self.scat[-1]) self.master.del_artist(self.line) del self.line
def __init__(self, outputPlot): self.decayValue = 0 self.outputPlot = outputPlot self.measurementPatch = Rectangle((0, 0), 1, 1, linewidth=1, color='gray', facecolor='none') self.statePatch = Circle((0, 0), 1, facecolor='blue') self.speedPatch = Arrow(0, 0, 3, 3) self.circlePatch = Circle((0, 0), 1, linewidth=1, color='red', facecolor='None') self.linePatch = ConnectionPatch((0, 0), (1, 1), 'data') self.model = 0 self.startLine = (0, 0) self.needToResetStartLine = True self.outputPlot.add_patch(self.measurementPatch) self.outputPlot.add_patch(self.statePatch) self.outputPlot.add_patch(self.speedPatch) self.outputPlot.add_patch(self.circlePatch) self.outputPlot.add_patch(self.linePatch) self.circlePatch.set_visible(False) self.linePatch.set_visible(False)
def connect_plots(ax0, ax1, x, y, delta): xy0 = (x + delta, y + delta) xy1 = (x - delta, y + delta) xy2 = (x + delta, y - delta) xy3 = (x - delta, y - delta) con0 = ConnectionPatch(xyA=xy0, xyB=xy1, coordsA="data", coordsB="data", axesA=ax0, axesB=ax1, color="m") ax0.add_artist(con0) con1 = ConnectionPatch(xyA=xy2, xyB=xy3, coordsA="data", coordsB="data", axesA=ax0, axesB=ax1, color="m") ax0.add_artist(con1) return con0, con1
def step_4(t,resonance,FID,fig,ax_one,ax_FID,ax_mult,ax_FT,freqs,nb_freq,trial,mult,integ,posinteg,neginteg,n): con_3 = ConnectionPatch(xyB=(1.2,0.5), xyA=(-0.2,0.5), coordsA="axes fraction", coordsB="axes fraction",axesA=ax_mult, axesB=ax_FT,color="red") con_3.set_arrowstyle("simple",head_length=0.5, head_width=1, tail_width=0.3) ax_mult.add_patch(con_3) ax_mult.fill_between(t,mult[n],where=mult[n]>0,interpolate=True,color="blue",label="Positive Areas") ax_mult.fill_between(t,mult[n],where=mult[n]<0,interpolate=True,color="red",label="Negative Areas") if ax_mult.get_legend() is None: ax_mult.legend(loc=1) ax_FT.plot(freqs[:n+1],integ[:n+1],linewidth=1,color="blue") ax_FT.plot([freqs[n]],[integ[n]],"ro") ann=ax_FT.annotate("Trial frequency {} Hz\nTotal area {}".format(round(freqs[n],1),round(round(posinteg[n],3)+round(neginteg[n],3),3)), xy=(freqs[n],integ[n]), xycoords='data', xytext=(-25, 10), textcoords='offset points', arrowprops=dict(facecolor='black',shrink=0.1,width=2,headwidth=10), horizontalalignment='right', verticalalignment='bottom') session["message"]="""The area under the multiplication curve (over the acquisition time) for a given trial frequency represents the relative intensity of the signal at this frequency.<br><br> For instance, the calculation for the trial frequency {} Hz from your FID gives (see graph 3):<br><br> <div style="background-color:white;font-weight:bold">Total area ( = Relative intensity) = <br><span style="color:blue">Positive areas</span> + <span style="color:red">Negative areas </span>= <span style="color:blue">({})</span> + <span style="color:red">({})</span> = {} area units</div><br> This point is reported on the final spectrum presented in graph 4.<br><br> The computer will repeat this operation with trial frequencies from {} to {} Hz in order to cover all our range of frequencies.<br><br> Press OK to access the spectrum generation (loading of the animation can take up to 1 min).<br><input type=submit name="msgOK" value="OK" class="control">""".format(round(freqs[n],1),round(posinteg[n],3),round(neginteg[n],3),round(round(posinteg[n],3)+round(neginteg[n],3),3),session["freq_min"]-1,session["freq_max"]+1) session["FT_step"]=4 return t,resonance,FID,fig,ax_one,ax_FID,ax_mult,ax_FT,freqs,nb_freq,trial,mult,integ,posinteg,neginteg,n,ann
def plot_warp(from_s, to_s, new_s, path, filename=None, fig=None, axs=None): """Plot the warped sequence and its relation to the original sequence and the target sequence. :param from_s: From sequence. :param to_s: To sequence. :param new_s: Warped version of from sequence. :param path: Optimal warping path. :param filename: Filename path (optional). :param fig: Matplotlib Figure object :param axs: Array of Matplotlib axes.Axes objects (length == 3) :return: Figure, list[Axes] """ try: import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.patches import ConnectionPatch except ImportError: logger.error( "The plot_warp function requires the matplotlib package to be installed." ) return if fig is None and axs is None: fig, axs = plt.subplots(nrows=3, ncols=1, sharex='all', sharey='all') elif fig is None or axs is None: raise TypeError( f'The fig and axs arguments need to be both None or both instantiated.' ) axs[0].plot(from_s, label="From") axs[0].legend() axs[1].plot(to_s, label="To") axs[1].legend() lines = [] line_options = {'linewidth': 0.5, 'color': 'orange', 'alpha': 0.8} for r_c, c_c in path: if r_c < 0 or c_c < 0: continue con = ConnectionPatch(xyA=[r_c, from_s[r_c]], coordsA=axs[0].transData, xyB=[c_c, to_s[c_c]], coordsB=axs[1].transData, **line_options) lines.append(con) axs[2].plot(new_s, label="From-warped") axs[2].legend() for i in range(len(to_s)): con = ConnectionPatch(xyA=[i, to_s[i]], coordsA=axs[1].transData, xyB=[i, new_s[i]], coordsB=axs[2].transData, **line_options) lines.append(con) for line in lines: fig.add_artist(line) if filename: plt.savefig(filename) plt.close() fig, axs = None, None return fig, axs
def _connect_axes(self, ax1, ax2): """Draws an arrow from ax1 to ax2. """ axis_center = self.get_cell_center() con = ConnectionPatch(xyA=axis_center, xyB=axis_center, coordsA="data", coordsB="data", axesA=ax1, axesB=ax2, color="red", mutation_scale=40, arrowstyle="->", shrinkB=5, shrinkA=5) ax1.add_artist(con) con = ConnectionPatch(xyA=axis_center, xyB=axis_center, coordsA="data", coordsB="data", axesA=ax2, axesB=ax1, color="red", mutation_scale=40, arrowstyle="<-", shrinkB=5, shrinkA=5) ax2.add_artist(con) ax1.plot(*axis_center, 'ro', markersize=10) ax2.plot(*axis_center, 'ro', markersize=10)
def plot_image_matching(x1, y1, x2, y2, bx1, by1, bx2, by2, img1, img2): f = plt.figure(figsize=(30, 30)) ax1 = f.add_subplot(121) ax2 = f.add_subplot(122) ax1.imshow(img1) ax1.axis('off') ax2.imshow(img2) ax2.axis('off') ax1.plot(x1, y1, 'ro', markersize=3) ax2.plot(x2, y2, 'ro', markersize=3) ax1.plot(bx1, by1, 'bo', markersize=3) ax2.plot(bx2, by2, 'bo', markersize=3) for i in range(len(x1)): con = ConnectionPatch(xyA=(x2[i], y2[i]), xyB=(x1[i], y1[i]), coordsA="data", coordsB="data", axesA=ax2, axesB=ax1, color="red") ax2.add_artist(con) for i in range(len(bx1)): con = ConnectionPatch(xyA=(bx2[i], by2[i]), xyB=(bx1[i], by1[i]), coordsA="data", coordsB="data", axesA=ax2, axesB=ax1, color="blue") ax2.add_artist(con)
def plot_synth_data_with_gates(models, concatenated_data, hparams, plot_config={}): plt.rcParams.update({'font.size': 20, 'font.family': 'serif'}) DEFAULT_PLOT_CONFIG.update(plot_config) plot_config = DEFAULT_PLOT_CONFIG features = ['M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8'] if plot_config['ncols'] < 7: raise ValueError('Need at least seven columns to display tree') input = SynthInput(hparams) fig = plt.figure(figsize=plot_config['figsize']) plt.tight_layout() grid = gridspec.GridSpec(nrows=3, ncols=plot_config['ncols'], figure=fig) grid.update(hspace=plot_config['hspace'], wspace=plot_config['wspace']) axes = [] axes.append(fig.add_subplot(grid[0,plot_config['ncols']//2])) axes.append(fig.add_subplot(grid[1,plot_config['ncols']//2 - 1])) axes.append(fig.add_subplot(grid[1,plot_config['ncols']//2 + 1])) axes.append(fig.add_subplot(grid[2,plot_config['ncols']//2 + 2])) fig.suptitle(plot_config['title'] ,x=.53, y=0, fontsize=25) for i in range(len(axes)): axes[i].set_xlim(right=plot_config['right']) axes[i].set_ylim(top=plot_config['top']) axes[i].set_xticks([], []) axes[i].set_yticks([], []) axes[0].set_ylabel('M2') axes[0].set_xlabel('M1') con = ConnectionPatch(xyA=(0., 0.), xyB=(.5, 1.), coordsA="axes fraction", \ coordsB="axes fraction", axesA=axes[0], axesB=axes[1], color='k', arrowstyle='-|>') axes[0].add_artist(con) axes[1].set_ylabel('M4') axes[1].set_xlabel('M3') con = ConnectionPatch(xyA=(1., 0.), xyB=(.5, 1.), coordsA="axes fraction", \ coordsB="axes fraction", axesA=axes[0], axesB=axes[2], color='k', arrowstyle='-|>') axes[0].add_artist(con) axes[2].set_ylabel('M6') axes[2].set_xlabel('M5') con = ConnectionPatch(xyA=(1., 0.), xyB=(.5, 1.), coordsA="axes fraction", \ coordsB="axes fraction", axesA=axes[2], axesB=axes[3], color='k', arrowstyle='-|>') axes[2].add_artist(con) axes[3].set_ylabel('M8') axes[3].set_xlabel('M7') flat_axes = np.array([axes[0], axes[2], axes[3], axes[1]]) for axis in flat_axes: axis.set_ylim(0, 1) axis.set_xlim(0, 1) init_gate_plotter = DataAndGatesPlotter(models['init'], concatenated_data) init_gate_plotter.plot_on_axes(flat_axes, hparams) final_gates_and_data_plotter = DataAndGatesPlotter(models['final'], concatenated_data, color='r') final_gates_and_data_plotter.plot_on_axes(flat_axes, hparams)
def plot_2dmap(self, data=None): """ Plots the distribution of the map in two dimensions, including the connections for neighbouring neurons. Only available if the dimensionality of the map is 2. Args: - data: (optional) an m by N array. If included, the map is plotted together with the provided data. """ if self.m != 2: raise ValueError("SOM dimensionality is not two") # Plot points first plt.figure() if data is not None: plt.scatter(data[0, :], data[1, :], alpha=0.5, edgecolors="none") plt.scatter(self.neurons[0, :], self.neurons[1, :], s=10, c="k") # Add the lines axis = plt.gca() i = 0 j = 0 for i in range(self.h - 1): for j in range(self.w - 1): # Connect to neurons in front of and below the neuron neuron_idx = self.neurons[:, np.ravel_multi_index( (i, j), (self.h, self.w))] neuron_front = self.neurons[:, np.ravel_multi_index( (i, j + 1), (self.h, self.w))] neuron_below = self.neurons[:, np.ravel_multi_index( (i + 1, j), (self.h, self.w))] axis.add_patch( ConnectionPatch(neuron_idx, neuron_front, "data")) axis.add_patch( ConnectionPatch(neuron_idx, neuron_below, "data")) # For the last column, connect to neuron below neuron_idx = self.neurons[:, np.ravel_multi_index((i, j + 1), (self.h, self.w))] neuron_below = self.neurons[:, np.ravel_multi_index((i + 1, j + 1), (self.h, self.w))] axis.add_patch(ConnectionPatch(neuron_idx, neuron_below, "data")) for j in range(self.w - 1): # For the last row, connect to neurons in front of the neuron neuron_idx = self.neurons[:, np.ravel_multi_index((self.h - 1, j), (self.h, self.w))] neuron_front = self.neurons[:, np.ravel_multi_index( (self.h - 1, j + 1), (self.h, self.w))] axis.add_patch(ConnectionPatch(neuron_idx, neuron_front, "data")) plt.show(block=False)
def add_connection(source_ax, source_data_coord, target_ax, target_data_coord): con = ConnectionPatch(xyA=source_data_coord, xyB=target_data_coord, coordsA='data', coordsB='data', axesA=source_ax, axesB=target_ax, arrowstyle='->', clip_on=False, linewidth=3) con.set_zorder(10) source_ax.add_artist(con)
def __init__(self, px_i, px_f, width): self.px_i = px_i self.px_f = px_f self.px_width = width # Find distance in pixels of line profile self.px_dist = int( np.round( np.hypot(self.px_f[0] - self.px_i[0], self.px_f[1] - self.px_i[1]))) self.s_dist = None # Calculate the angle the line makes with the x-axis self.line_vec = np.array( [self.px_f[0] - self.px_i[0], self.px_f[1] - self.px_i[1]]) self.angle = np.angle(self.line_vec[0] + self.line_vec[1] * 1j, deg=False) # Calculate the offset in X and Y for the linewidth start # and end points at the start point for the line profile self.xyA_i = ( (self.px_i[0] - width / 2 * np.sin(self.angle)), (self.px_i[1] + width / 2 * np.cos(self.angle)), ) self.xyB_i = ( (self.px_i[0] + width / 2 * np.sin(self.angle)), (self.px_i[1] - width / 2 * np.cos(self.angle)), ) self.cpatch_i = ConnectionPatch( xyA=self.xyA_i, xyB=self.xyB_i, coordsA="data", coordsB="data", ) self.cpatch_line = ConnectionPatch( xyA=self.px_i, xyB=self.px_f, coordsA="data", coordsB="data", ) self.xyA_f = ( (self.px_f[0] - width / 2 * np.sin(self.angle)), (self.px_f[1] + width / 2 * np.cos(self.angle)), ) self.xyB_f = ( (self.px_f[0] + width / 2 * np.sin(self.angle)), (self.px_f[1] - width / 2 * np.cos(self.angle)), ) self.cpatch_f = ConnectionPatch( xyA=self.xyA_f, xyB=self.xyB_f, coordsA="data", coordsB="data", )
def _plot_feature_to_kernel_lines(kernel_matrix_2d, feature_matrix_2d, feature_row_at_center, feature_column_at_center, kernel_axes_object, feature_axes_object): """Plots lines between feature map and kernel. :param kernel_matrix_2d: See doc for `_plot_kernel`. :param feature_matrix_2d: Same. :param feature_row_at_center: Same. :param feature_column_at_center: Same. :param kernel_axes_object: Axes on which kernel is plotted (instance of `matplotlib.axes._subplots.AxesSubplot`). :param feature_axes_object: Axes on which feature map is plotted (instance of `matplotlib.axes._subplots.AxesSubplot`). """ num_feature_rows = feature_matrix_2d.shape[0] num_feature_columns = feature_matrix_2d.shape[1] num_kernel_rows = kernel_matrix_2d.shape[0] first_feature_row = max([feature_row_at_center - 1.5, -0.5]) last_feature_row = min( [feature_row_at_center + 1.5, num_feature_rows - 0.5]) last_feature_column = min( [feature_column_at_center + 1.5, num_feature_columns - 0.5]) center_row_from_bottom = num_feature_rows - feature_row_at_center - 1 first_kernel_row = -0.5 + max([1 - feature_row_at_center, 0]) last_kernel_row = 0.5 + min( [1 + center_row_from_bottom, num_kernel_rows - 1]) first_kernel_column = -0.5 + max([1 - feature_column_at_center, 0]) this_connection_object = ConnectionPatch( xyA=(first_kernel_column, first_kernel_row), xyB=(last_feature_column, first_feature_row), coordsA='data', coordsB='data', axesA=kernel_axes_object, axesB=feature_axes_object, color=FEATURE_TO_KERNEL_LINE_COLOUR, linewidth=FEATURE_TO_KERNEL_LINE_WIDTH, linestyle='dashed') kernel_axes_object.add_artist(this_connection_object) this_connection_object = ConnectionPatch( xyA=(first_kernel_column, last_kernel_row), xyB=(last_feature_column, last_feature_row), coordsA='data', coordsB='data', axesA=kernel_axes_object, axesB=feature_axes_object, color=FEATURE_TO_KERNEL_LINE_COLOUR, linewidth=FEATURE_TO_KERNEL_LINE_WIDTH, linestyle='dashed') kernel_axes_object.add_artist(this_connection_object)
def step_1(): t,resonance,FID,fig,ax_one,ax_FID,ax_mult,ax_FT=draw_freq() con_2 = ConnectionPatch(xyA=(0.5,-0.2), xyB=(0.5,1.15), coordsA="axes fraction", coordsB="axes fraction",axesA=ax_FID, axesB=ax_mult,color="red") con_2.set_arrowstyle("simple",head_length=0.5, head_width=1, tail_width=0.3) ax_FID.add_patch(con_2) freqs=np.arange(session["freq_min"]-1,session["freq_max"]+1,session["freq_res"]) freqs=np.append(freqs,session["freq_max"]+1) nb_freq=freqs.size trial=np.zeros((nb_freq,session["nb_points"])) mult=np.zeros((nb_freq,session["nb_points"])) integ=np.zeros(nb_freq) posinteg=np.zeros(nb_freq) neginteg=np.zeros(nb_freq) for i,freq in enumerate(freqs): trial[i]=np.cos(2*np.pi*freq*t) mult[i]=trial[i]*FID posmult=np.zeros(session["nb_points"]) negmult=np.zeros(session["nb_points"]) for nn,ii in enumerate(mult[i]): if ii >0: posmult[nn]=ii if ii <0: negmult[nn]=ii posinteg[i]=np.trapz(posmult,t) neginteg[i]=np.trapz(negmult,t) integ[i]=np.trapz(mult[i],t) if freq<=session["freq_min"]: n=i ax_FT.set_ylim(integ.min()-(integ.max()-integ.min())*0.05,integ.max()+(integ.max()-integ.min())*0.4) ax_FID.plot(t,trial[n],linewidth=1,color="magenta",alpha=0.5) ax_mult.plot(t,mult[n],linewidth=1,color="black",alpha=0.5) ax_FID.legend(("FID","Trial Frequency {} Hz".format(round(freqs[n],1))),loc=1) session["message"]="""The acquired signal will be processed and the computer will try to find all the frequencies from which your FID is composed.<br><br> To do this, it will multiply your FID by cosine functions with increasing frequencies, covering all our frequencies range from {} to {} Hz.<br> We will call these cosine functions "Trial Frequencies".<br><br> The multiplication is done "point by point", as shown in the example below: <br><br> <img src="/static/img1.png" style="width:95%"/><br><br> The result of the multiplication of your FID by the trial frequency {} Hz is shown in graph 3.<br> <input type=submit name="msgOK" value="Next" class="control">""".format(session["freq_min"],session["freq_max"],round(freqs[n],1)) session["FT_step"]=1 return t,resonance,FID,fig,ax_one,ax_FID,ax_mult,ax_FT,freqs,nb_freq,trial,mult,integ,posinteg,neginteg,n
def linking_lines( fig_: Figure, axes_A: Axes, axes_B: Axes, axes_C: Axes, axes_D: Axes, color_: str = brown_, ) -> None: r""" Draw lines linking features in the main plot to zoom insets. Args: fig_: Figure to act on axes_A: Axes of zoom box A axes_B: Axes of zoom box B axes_C: Axes of zoom box C axes_D: Axes of zoom box D """ joins: List[ConnectionPatch] = [None] * 3 kwargs = dict(color=color_, linestyle=":") joins[0] = ConnectionPatch( xyA=(0.2, 0), coordsA=axes_D.transData, xyB=(0.4, 1), coordsB=axes_A.transData, **kwargs, ) joins[1] = ConnectionPatch( xyA=(1, 0.00), coordsA=axes_D.transData, xyB=(0, 0.9), coordsB=axes_B.transData, **kwargs, ) joins[2] = ConnectionPatch( xyA=(1, 0.60), coordsA=axes_D.transData, xyB=(0, 0.8), coordsB=axes_C.transData, **kwargs, ) for join_ in joins: fig_.add_artist(join_)
def plotting_pairs(self, BLPoints, FUPoints): ''' Plotting the point pairs next to each other in one plot. :param BLPoints: Baseline points -- shape (N,2) :param FUPoints: Follow-up points -- shape (N,2) Function for plotting pairs of points in two transformed images. ''' fig = plt.figure(1) a1 = fig.add_subplot(1, 2, 1) self.plotting_points(self.bl, BLPoints, number=True) a2 = fig.add_subplot(1, 2, 2) self.plotting_points(self.fu, FUPoints, number=True) for idx in range(BLPoints.shape[0]): xbl = BLPoints[idx][0] ybl = BLPoints[idx][1] xfu = FUPoints[idx][0] yfu = FUPoints[idx][1] con = ConnectionPatch(xyA=(xfu, yfu), xyB=(xbl, ybl), coordsA="data", coordsB="data", axesA=a2, axesB=a1, color="red") a2.add_artist(con)
def vmarker(x0, x1, ax0, ax1, **kwargs): xy0 = (x0, ax0.get_ylim()[0]) xy1 = (x1, ax1.get_ylim()[1]) ax0.axvline(x0, **kwargs) ax1.axvline(x1, **kwargs) con = ConnectionPatch(xy0, xy1, 'data', 'data', ax0, ax1, **kwargs) ax0.add_artist(con)
def visualize_pair(self, image1, image2): img1 = mpimg.imread(image1) img2 = mpimg.imread(image2) x1 = self.point1.x y1 = self.point1.y x2 = self.point2.x y2 = self.point2.y fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1) ax1.imshow(img1) ax1.plot(x1, y1, 'r*') ax2 = fig.add_subplot(1, 2, 2) ax2.imshow(img2) ax2.plot(x2, y2, 'r*') con = ConnectionPatch(xyA=(x2, y2), xyB=(x1, y1), coordsA="data", coordsB="data", axesA=ax2, axesB=ax1, color="red") ax2.add_artist(con) fig.savefig('result.png')
def show(self, filename=None, **kwargs): tsx, tsy = kwargs.get('tsx', 0), kwargs.get('tsy', 0) fig, ax = plt.subplots(figsize=self.figsize) ax.axis('equal') ax.set_xticks([]), ax.set_yticks([]) sns.despine(left=True, bottom=True, right=True, top=True) ax.set_xlim((min(self.ymin, self.xmin), max(self.ymax, self.xmax))) ax.set_ylim((min(self.ymin, self.xmin), max(self.ymax, self.xmax))) for name, v in self._vertices.items(): vx, vy = v.position c = Circle((vx, vy), v.radius, zorder=20) c.set_edgecolor(v.rcolor) c.set_facecolor(v.color) ax.annotate(name, xy=(vx, vy), fontsize=v.tsize, ha='center', xytext=(vx + tsx, vy + tsy), color=v.tcolor, zorder=21) ax.add_artist(c) for e in self._alist[name]: l = ConnectionPatch(e.a.position, e.b.position, 'data') ax.add_artist(l) plt.close() return fig
def animate(frame): ax.patches = [] c_B = cum_orbits[0, int(frame)] for j, i in enumerate(draw_idx): c_A, c_B = cum_orbits[i, int(frame)], cum_orbits[i + 1, int(frame)] r = radius[i] ax.add_patch( plt.Circle((c_A.real, c_A.imag), r, fill=False, linestyle="dotted", linewidth=args.circle_width, color=args.circle_color)) ax.add_patch( ConnectionPatch((c_A.real, c_A.imag), (c_B.real, c_B.imag), ax.transData, arrowstyle="-", linewidth=args.vector_width, color=args.vector_color)) x, y = cum_orbits[-1, :int(frame) + 1].real, cum_orbits[-1, :int(frame) + 1].imag pl.set_data(x, y) return ax.patches + [ pl, ]
def example(): from matplotlib import pyplot as plt import numpy as np # todo: read the example image from the papers source directory image1 = imread(wrapper.source_directory + '/adam1.png') image2 = imread(wrapper.source_directory + '/adam2.png') # todo: call the wrapped function(s) with a valid set of arguments matches, keys1, keys2 = wrapper.asift(image1, image2) # todo: display the results fig = plt.figure(figsize=(10, 5)) ax1 = fig.add_subplot(121) plt.imshow(image1, cmap='Greys_r') ax2 = fig.add_subplot(122) plt.imshow(image2, cmap='Greys_r') for x1, y1, x2, y2 in matches[::1, :]: con = ConnectionPatch(xyA=(x2, y2), xyB=(x1, y1), coordsA="data", coordsB="data", axesA=ax2, axesB=ax1, shrinkB=5, color='r') ax2.add_artist(con) plt.draw() plt.show() print('done')
def draw_pitch(ax): # focus on only half of the pitch #Pitch Outline & Centre Line Pitch = Rectangle([0,0], width = 120, height = 80, fill = False) #Left, Right Penalty Area and midline LeftPenalty = Rectangle([0,22.3], width = 14.6, height = 35.3, fill = False) RightPenalty = Rectangle([105.4,22.3], width = 14.6, height = 35.3, fill = False) midline = ConnectionPatch([60,0], [60,80], "data", "data") #Left, Right 6-yard Box LeftSixYard = Rectangle([0,32], width = 4.9, height = 16, fill = False) RightSixYard = Rectangle([115.1,32], width = 4.9, height = 16, fill = False) #Prepare Circles centreCircle = plt.Circle((60,40),8.1,color="black", fill = False) centreSpot = plt.Circle((60,40),0.71,color="black") #Penalty spots and Arcs around penalty boxes leftPenSpot = plt.Circle((9.7,40),0.71,color="black") rightPenSpot = plt.Circle((110.3,40),0.71,color="black") leftArc = Arc((9.7,40),height=16.2,width=16.2,angle=0,theta1=310,theta2=50,color="black") rightArc = Arc((110.3,40),height=16.2,width=16.2,angle=0,theta1=130,theta2=230,color="black") element = [Pitch, LeftPenalty, RightPenalty, midline, LeftSixYard, RightSixYard, centreCircle, centreSpot, rightPenSpot, leftPenSpot, leftArc, rightArc] for i in element: ax.add_patch(i)
def draw(self, img_q, img_t, pt_qt): import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from matplotlib.patches import ConnectionPatch fig, (ax_q, ax_t) = plt.subplots(1, 2, figsize=(8, 4)) for pt_q, pt_t in pt_qt: con = ConnectionPatch(pt_t, pt_q, coordsA='data', coordsB='data', axesA=ax_t, axesB=ax_q, color='g', linewidth=0.5) ax_t.add_artist(con) ax_q.plot(pt_q[0], pt_q[1], 'rx') ax_t.plot(pt_t[0], pt_t[1], 'rx') ax_q.imshow(img_q) ax_t.imshow(img_t) ax_q.axis('off') ax_t.axis('off') plt.subplots_adjust(wspace=0, hspace=0) plt.show()
def drawSPC(self, currentClass, fig, ogX, ogY): # Draws the CPC by resizing the figure and creating the graph for currentIndex in range(len(ogX)): n = len(fig.axes) for b in range(n): fig.axes[b].change_geometry(currentClass, len(ogX), b + 1) # Resizing (row, column, position) ax = fig.add_subplot(currentClass, len(ogX), n + 1) ax.set_xlabel("X " + str(currentIndex * 2 + 1)) # Styling the graph ax.set_ylabel("X " + str(currentIndex * 2 + 2)) if (currentIndex == 0): ax.set_title("SPC for Class: " + str(currentClass)) xMin = min(ogX) - 1 xMax = max(ogX) + 1 yMin = min(ogY) - 1 yMax = max(ogY) + 1 plt.xlim(float(xMin), float(xMax)) plt.ylim(float(yMin), float(yMax)) ax.plot(ogX[currentIndex], ogY[currentIndex], 'r') # Plotting the graph pax = fig.axes[n] if (currentIndex > 0): xy = ( ogX[currentIndex - 1], ogY[currentIndex - 1]) # These are for original values to be graphed in SPC ab = (ogX[currentIndex], ogY[currentIndex]) con = ConnectionPatch(xyA=ab, xyB=xy, coordsA="data", coordsB="data", axesA=fig.axes[n], axesB=fig.axes[n - 1], color="purple") pax.add_artist(con) pax.plot(ogX[currentIndex], ogY[currentIndex], 'ro', markersize=10) # Plot the SPC points on each graph else: pax.plot(ogX[currentIndex], ogY[currentIndex], 'ro', markersize=10) # Plot the SPC points on each graph
def plot_corr(img1, img2, img1_pts, img2_pts, vsplit=False, figsize=(20, 15)): plot1 = 211 plot2 = 212 if vsplit: plot1 = 121 plot2 = 122 fig = plt.figure(figsize=figsize) ax1 = plt.subplot(plot1) ax1.imshow(img1, cmap='gray', aspect = "auto") ax1.scatter(img1_pts[:, 0], img1_pts[:, 1], marker='+') ax1.set_xticklabels([]) ax1.set_yticklabels([]) ax2 = plt.subplot(plot2) ax2.imshow(img2, cmap='gray', aspect = "auto") ax2.scatter(img2_pts[:, 0], img2_pts[:, 1], marker='+') ax2.set_xticklabels([]) ax2.set_yticklabels([]) for i in range(len(img1_pts)): xy1 = (img1_pts[i,0],img1_pts[i,1]) xy2 = (img2_pts[i,0],img2_pts[i,1]) con = ConnectionPatch(xyA=xy2, xyB=xy1, coordsA="data", coordsB="data", axesA=ax2, axesB=ax1, color='#53F242') ax2.add_artist(con) plt.subplots_adjust(wspace=0, hspace=0) # plt.tight_layout() plt.show()
def addArrow(ax, cx, xdiff, cy, ydiff, text, color="k", ha="left", va="center", arrowstyle="-|>", shrinkA=2, shrinkB=4, xlog=False, ylog=True): x = cx * xdiff if xlog else cx + xdiff y = cy * ydiff if ylog else cy + ydiff con = ConnectionPatch(xyA=(x, y), xyB=(cx, cy), coordsA="data", coordsB="data", arrowstyle=arrowstyle, shrinkA=shrinkA, shrinkB=shrinkB, mutation_scale=20, fc="w", color=color) # connectionstyle="arc3,rad=0.3" ax.add_artist(con) ax.annotate(text, xy=(x, y), ha=ha, va=va, color=color) #,box=dict(boxstyle="round", fc="w")
def plot_expected_lengths(lengths, batch_sizes, choose_length, markers=[], n_batches=10000): fig, axarr = plt.subplots(len(batch_sizes), 1, figsize=(14, 20), sharex=True) expected_lengths = {} for i, batch_size in enumerate(batch_sizes): maxs = [] for _ in tqdm(range(n_batches), disable=False): val = choose_length(np.random.choice(lengths, batch_size)) maxs.append(math.ceil(val)) pd.Series(maxs).plot.hist(bins=50, ax=axarr[i], density=True, color='black', edgecolor='white', alpha=0.1) expected = np.mean(maxs) expected_lengths[batch_size] = expected max_y = axarr[i].get_ylim()[1] axarr[i].vlines([expected], 0, 1e3, 'limegreen', lw=4) axarr[i].set_ylim([0, max_y]) axarr[i].set_xlim([0, max(lengths)]) axarr[i].set_ylabel(f'batch_size={batch_size}', rotation=0) axarr[i].yaxis.set_label_coords(-0.1, 0.45) axarr[i].set_yticks([]) for marker in markers: con = ConnectionPatch(xyA=(marker, axarr[0].get_ylim()[1]), xyB=(marker, 0), coordsA='data', coordsB='data', axesA=axarr[0], axesB=axarr[-1], color='red', lw=4) axarr[0].add_artist(con) axarr[0].set_zorder(1) axarr[0].set_title(f'Expected sequence lengths with various batch sizes (n per batch = {n_batches})') plt.subplots_adjust(hspace=0) return expected_lengths
def plot_graph(graph, ax, n, weighted, shrinkA, shrinkB, layout, polygon_radius, attr, arrowstyle, weight_color, arrow_color): """ creates a plot of nodes and edges connected by a ConnectionPatch object. """ for node in plot_graph.nodes: x_i, y_i = plot_graph.points[node] for adj_node in node.adjacent_nodes: _from = graph.get_node_id(node) _to = graph.get_node_id(adj_node) edge = graph.connections[_from][_to] A_color = "k" if not arrow_color else edge.color A_width = edge.linewidth if not edge.linewidth else edge.linewidth * 4 x_prime, y_prime = plot_graph.points[adj_node] con = ConnectionPatch((x_i, y_i), (x_prime, y_prime), COORDSA, COORDSB, arrowstyle=arrowstyle, shrinkA=shrinkA, shrinkB=shrinkB, mutation_scale=plot_graph.scale, fc=A_color, linewidth=A_width, edgecolor=A_color) if weighted: T_color = "k" if not weight_color else A_color x_mid, y_mid = (x_prime + x_i) * 0.5, (y_prime + y_i) * 0.5 weight = edge.weight fontsize = 12 / n + 12 ax.text(x_mid, y_mid, str(weight), fontsize=edge.fontsize * fontsize + fontsize, color=T_color) ax.add_artist(con)
def draw_matches(img1, keypoints1, img2, keypoints2, plot_title=""): """ Draws matches of keypoints between img1 and img2. :param img1: the first image :param keypoints1: the first image's keypoints :param img2: the second image :param keypoints2: the second image's keypoints :param plot_title: the title of the plot """ figure = plt.figure(figsize=(10, 5)) ax1 = plt.subplot(1, 2, 1) ax2 = plt.subplot(1, 2, 2) img1 = cv2.drawKeypoints(img1, keypoints1, None) img2 = cv2.drawKeypoints(img2, keypoints2, None) ax1.imshow(img1) ax2.imshow(img2) for kp1, kp2 in zip(keypoints1, keypoints2): con = ConnectionPatch(xyA=kp2.pt, xyB=kp1.pt, coordsA="data", coordsB="data", axesA=ax2, axesB=ax1, color=np.random.rand(3, )) ax2.add_patch(con) plt.title(plot_title) plt.show() figure.savefig("data/results/" + plot_title.replace(" ", "-").replace(".", "-") + '.png', dpi=100, bbox_inches='tight')
def example(): # todo: read the example image from the papers source directory image1=imread(wrapper.source_directory+'/examples/gobelet.png') image2=imread(wrapper.source_directory+'/examples/gobelet2.png') # todo: call the wrapped function(s) with a valid set of arguments #keys1=wrapper. keys1=wrapper.extract_surf(image1) keys2=wrapper.extract_surf(image2) matches=wrapper.match_surf(keys1,keys2) # todo: display the results fig = plt.figure(figsize=(10,5)) ax1 = fig.add_subplot(121) plt.imshow(image1) ax2 = fig.add_subplot(122) plt.imshow(image2) for x1,y1,x2,y2 in matches: con = ConnectionPatch(xyA=(x2, y2), xyB=(x1,y1), coordsA="data", coordsB="data" , axesA=ax2, axesB=ax1, shrinkB=5,color='r') ax2.add_artist(con) plt.draw() plt.show() print 'done'
def plot_transfer(self, transfer, source_plates, target_plates, axes=None): """Plot the plates and add and arrow for the transfer""" fig, axes, axes_dict = self.plot_plates(source_plates, target_plates, axes=axes) source_well = transfer.source_well source_plate = source_well.plate source_ax = axes_dict[source_plate.name] x, y = source_well.coordinates[::-1] source_coord = x, source_plate.num_rows - y + 1 target_well = transfer.destination_well target_plate = target_well.plate target_ax = axes_dict[target_plate.name] x, y = target_well.coordinates[::-1] target_coord = x, target_plate.num_rows - y + 1 target_ax.set_zorder(source_ax.get_zorder() - 1) arrow = ConnectionPatch( xyA=source_coord, xyB=target_coord, coordsA="data", coordsB="data", axesA=source_ax, axesB=target_ax, shrinkB=5.0, lw=2, facecolor='black', arrowstyle="wedge", zorder=1000) source_ax.add_artist(arrow) return fig, axes
ax2.set_title('Age of approvers') ax2.legend(('50-65', 'Over 65', '35-49', 'Under 35')) ax2.axis('off') ax2.set_xlim(- 2.5 * width, 2.5 * width) # use ConnectionPatch to draw lines between the two plots # get the wedge data theta1, theta2 = ax1.patches[0].theta1, ax1.patches[0].theta2 center, r = ax1.patches[0].center, ax1.patches[0].r bar_height = sum([item.get_height() for item in ax2.patches]) # draw top connecting line x = r * np.cos(np.pi / 180 * theta2) + center[0] y = np.sin(np.pi / 180 * theta2) + center[1] con = ConnectionPatch(xyA=(- width / 2, bar_height), xyB=(x, y), coordsA="data", coordsB="data", axesA=ax2, axesB=ax1) con.set_color([0, 0, 0]) con.set_linewidth(4) ax2.add_artist(con) # draw bottom connecting line x = r * np.cos(np.pi / 180 * theta1) + center[0] y = np.sin(np.pi / 180 * theta1) + center[1] con = ConnectionPatch(xyA=(- width / 2, 0), xyB=(x, y), coordsA="data", coordsB="data", axesA=ax2, axesB=ax1) con.set_color([0, 0, 0]) ax2.add_artist(con) con.set_linewidth(4) plt.show()