def __plot__(self, svcHand, title, X, y): # set up some plot stuff title = "Support Vector Machine: {} kernel".format(title) x_min, x_max = X[:, 0].min - 1, X[:, 1].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # get our figure plt.figure(self._figNum) # add plot and show decision boundaries plt.add_subplot(plotNum) # make sure window is open plt.draw() plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral) # plot linsvc contours for i, cl in enumerate((linsvc)): Z = cl.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) self._fig.contourf(xx, yy, Z) plt.xlabel('X') plt.ylabel('Y') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.title(title) plt.show()
def test_generator(self, n_samples=5): noise = self.generate_latent_samples(size=n_samples, invert_labels=False) outs = self.generator.predict(noise) for i in range(outs.shape[0]): plt.add_subplot(1, n_samples, i + 1) plt.axis('off') plt.imshow(outs[i, :, :, 0].reshape(28, 28), cmap='gray') plt.show() print('\n')
def merge_plots_and_latex(): latex,plot = print_latex(),show_plots() print type(latex),type(plot) merged_figure = plt.figure("Relat Completo",facecolor = "white") plt.add_subplot(11,latex) plt.show()
def run(self, tps, snap, data, para=None): plt = self.app.show_plot(para['title']) if para['dir']: data[para['cn']].plot.barh(stacked=para['stack'], grid=para['grid'], title=para['title'], ax=plt.add_subplot()) else: data[para['cn']].plot.bar(stacked=para['stack'], grid=para['grid'], title=para['title'], ax=plt.add_subplot()) plt.Show()
def visualize_image(imgs, img_titles, gray=False): rows, cols = 3, 3 plt.figure(figsize=(20, 20)) for i, img in enumerate(imgs): plt.add_subplot(rows, cols, i+1) if gray: plt.imshow(img, cmap='gray') else: plt.imshow(img) plt.title(img_titles[i]) plt.show()
def run(self, tps, snap, data, para=None): plt = self.app.show_plot(para['title']) data[para['cn']].plot(lw=para['lw'], grid=para['grid'], title=para['title'], ax=plt.add_subplot()) plt.Show()
def show3d(self, xdim, ydim, zdim=None, ax=None, label=None): values = np.array(self.stor) if (ax is None): ax = plt.add_subplot(111, projection='3d') zvalue = values[:, zdim] ax.plot(values[:, xdim], values[:, ydim], zvalue, label=label) return ax
def visualize(): global csv_name df = pd.read_csv(csv_name) days = df.iloc[:, 0] infected = df.iloc[:, 2] isolated = df.iloc[:, 9] sev_inf = df.iloc[:, 4] quarantined = df.iloc[:, 5] immunized = df.iloc[:, 6] susceptible = df.iloc[:, 7] dead = df.iloc[:, 8] window_vis = tk.Toplevel(root) window_vis.geometry("1000x1000") window_vis.title("Visualization") plt = Figure() csv_name = csv_name.split("/")[-1] csv_name = csv_name.split(".")[0] plt.suptitle('Visualization for ' + csv_name, fontsize=16) plt1 = plt.add_subplot(211) plt1.plot(days, infected, color='tab:blue', marker='.', label='Infected') plt1.plot(days, isolated, color='brown', label='Isolated', marker='.') plt1.plot(days, quarantined, color='yellow', label='Quarantined', marker='.') plt1.plot(days, sev_inf, color='red', label='Severely Infected', marker='.') plt1.plot(days, immunized, color='gold', label='Immunized', marker='.') plt1.plot(days, dead, color='black', label='Dead', marker='.') plt1.legend() plt1.grid() plt2 = plt.add_subplot(212) plt2.plot(days, dead, color='black', marker='.', label='Dead') plt2.plot(days, sev_inf, color='red', marker='.', label='Severe Infected') plt2.legend() plt2.grid() canvas = FigureCanvasTkAgg(plt, master=window_vis) canvas.draw() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2Tk(canvas, window_vis) toolbar.update() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def run(self, tps, snap, data, para=None): plt = self.app.show_plot(para['title']) data[para['cn']].plot.area(stacked=para['stack'], alpha=para['alpha'], grid=para['grid'], title=para['title'], ax=plt.add_subplot()) plt.Show()
def run(self, tps, snap, data, para=None): plt = self.app.show_plot(para['title']) data[para['cn']].plot.box(by=None, vert=~para['hor'], grid=para['grid'], title=para['title'], ax=plt.add_subplot()) plt.Show()
def run(self, tps, snap, data, para=None): plt = self.app.show_plot(para['title']) if para['overlay']: data[para['cn']].plot.hist(stacked=para['stack'], bins=para['bins'], alpha=para['alpha'], orientation=para['dir'], grid=para['grid'], title=para['title'], ax=plt.add_subplot()) else: data[para['cn']].hist(stacked=para['stack'], bins=para['bins'], alpha=para['alpha'], orientation=para['dir'], grid=para['grid'], ax=plt.add_subplot()) plt.Show()
def scree(eigVals,npc=50): #Assume the list is all of the eigenvalues rel = cumsum(eigVals)/eigVals.sum() x = arange(len(rel))+1 fig = plt.figure() ax = plt.add_subplot(111) ax.bar(x,rel,width=0.5) postdoc.adjust_spines(ax,['bottom','left']) ax.set_xlabel('Eigenvector') ax.set_ylabel('Fraction of variance') plt.show()
def ap_correction(image,syntax,df): import numpy as np from astropy.stats import sigma_clip import matplotlib.pyplot as plt from autophot.packages.functions import mag import logging logger = logging.getLogger(__name__) ap_diff = mag(df['flux_inf_ap'] / df['flux_ap'],0) ap_diff = ap_diff[~np.isnan(ap_diff)] corr_mask = np.array(~sigma_clip(ap_diff, sigma = syntax['ap_corr_sigma']).mask) ap_corr = ap_diff[corr_mask] if syntax['ap_corr_plot']: fig = plt.figure(figsize = (10,6)) fig.suptitle('Aperture Corrections') ax1 = plt.add_subplot(121) ax1.hist(ap_diff,bins = 'auto',label = 'Before Cliiping') ax2 = plt.add_subplot(122) ax2.hist(ap_corr,bins = 'auto',label = 'After Cliiping') ax1.set_xlabel('Aperture Correction magnitude') ax1.set_ylabel('Occurence') ax1.legend(loc = 'best') ax2.set_xlabel('Aperture Correction magnitude') ax2.set_ylabel('Occurence') ax2.legend(loc = 'best') plt.show() logger.info('Aperture correction: %.3f +/- %.3f' % (np.nanmean(ap_corr),np.nanstd(ap_corr))) ap_corr = np.nanmean(ap_corr) return ap_corr
def co_embed(normalized_full_data, normalized_downsampled_data, save_dir=None): # convert pandas dataframe to numpy array normalized_full_data, normalized_downsampled_data = normalized_full_data.values, normalized_downsampled_data.values # combine data combined_data = np.concatenate( (normalized_full_data, normalized_downsampled_data)) # sample id sample_id = [0] * normalized_full_data.shape[0] + [ 1 ] * normalized_downsampled_data.shape[0] pca = PCA(n_components=200, svd_solver='randomized') principalComponents = pca.fit_transform(combined_data) umap_result = UMAP(n_neighbors=30, metric='euclidean', random_state=7).fit_transform(principalComponents) color_pallete = ['g', 'r'] file_names = ['full data', 'downsampled data'] # plotting fig = plt.figure(figsize=(8 * 3, 6 * 1)) ax = plt.add_subplot(1, 3, 1) for j in np.unique(sample_id): id_s = sample_id == j ax.scatter(umap_result[id_s, 0], umap_result[id_s, 1], s=2, c=color_pallete[j], label=file_names[j]) lgnd = plt.legend(loc='left', bbox_to_anchor=(1.01, 1.01), fontsize=12, markerscale=3) ax.set_xlabel('UMAP-1') ax.set_ylabel('UMAP-2') ax.set_xticks([], []) ax.set_yticks([], []) for item in np.unique(sample_id): ax = fig.add_subplot(1, 3, item + 2) id_s = sample_id == j ax.scatter(umap_result[:, 0], umap_result[:, 1], s=0.1, c='k') ax.scatter(umap_result[id_s, 0], umap_result[id_s, 1], s=5, c=color_pallete[item]) ax.set_xticks([], []) ax.set_yticks([], []) if save_dir is not None: plt.savefig(save_dir) return umap_result
def plot_only_graph(fol, data_to_show_in_graph, time_range_tup, xtick_dt, xlabel='', ylabels=(), xticklabels=(), ylim=None, images=None, fol2='', graph2_ax=None, do_show=False): import matplotlib.pyplot as plt plt = plt.figure() ax = plt.add_subplot(111) if len(time_range_tup) == 3: time_range = np.arange(time_range_tup[0], time_range_tup[1], time_range_tup[2]) xticks = np.arange(time_range_tup[0], len(time_range), xtick_dt).tolist() else: time_range = np.arange(time_range_tup[0]) xticks = None plot_graph(ax, data_to_show_in_graph, time_range, xticks, fol, fol2='', graph2_ax=None, xlabel=xlabel, ylabels=ylabels, xticklabels=xticklabels, ylim=ylim, images=None, green_line=False) if do_show: plt.show() plt.savefig(op.join(fol, 'graph.jpg'))
def plot(): fig = plt.figure(figsize = (10,5)) ax = plt.add_subplot(111, projection="mollweide", axisbg ='LightCyan') ax.title('SNIa Mollweide Projection from the OSC Data )') ax.grid(True) ax.plot(raRad, decRad) drawRectangles = False if drawRectangles: for i in range(37): plt.axvline(i * 10, ymin = 0.02, ymax = 0.96, color='k') for i in range(19): plt.axhline(i * 10 - 90, xmin = 0.03, xmax = 0.97, color='k') plt.show()
def plotter(data): plt = Figure(figsize=(5, 4), dpi=100) lower_limit = 0 upper_limit = 100 figure_count = 1 for _ in range(12): temp = [] for index in range(lower_limit, upper_limit): temp.append(float(data[index])) a = plt.add_subplot(4, 3, figure_count) a.plot(temp) lower_limit = upper_limit upper_limit = upper_limit + 100 figure_count = figure_count + 1 return plt, a
def run(self, tps, snap, data, para=None): rs = data[ para['rs']] * para['s'] if para['rs'] != 'None' else para['s'] cs = data[para[ 'cs']] if para['cs'] != 'None' else '#%.2x%.2x%.2x' % para['c'] cm = ColorManager.get(para['cm']) / 255.0 cm = None if para['cs'] == 'None' else colors.ListedColormap(cm, N=256) plt = self.app.show_plot(para['title']) data.plot.scatter(x=para['x'], y=para['y'], s=rs, c=cs, alpha=para['alpha'], cmap=cm, grid=para['grid'], title=para['title'], ax=plt.add_subplot()) plt.Show()
def makePitchRing(indexes): circle = np.linspace(0, 2 * np.pi, 64) r = 1.0 x = r * np.sin(circle) y = r * np.cos(circle) # the note locations. base_dots = np.linspace(0, 2 * np.pi, 13) xd = r * np.sin(base_dots) yd = r * np.cos(base_dots) # the text locations r = 1.15 xt = r * np.sin(base_dots) yt = r * np.cos(base_dots) # ======================== # THIS probably won't let it be embedded in another figure ! #fig1 = plt.figure() #ax1 = fig1.add_subplot(111, aspect='equal') ax1 = plt.add_subplot(111, aspect='equal') # (0) plot a filled square with a filled circle in it... # patches.Rectangle((x,y,lower left corner),width,height) #ax1.add_patch(patches.Rectangle((0.1, 0.1),0.5,0.5,facecolor="red")) ax1.add_patch( patches.Rectangle((-1.25, -1.25), 2.5, 2.5, facecolor=[0.6, 0.6, 0.6])) ax1.plot(x, y, 'k-') ax1.plot(xd, yd, 'w.') radius_norm = 0.08 # radius normalized, scaled to size of box for ind, interval in enumerate(indexes): # print(ind,interval) ax1.add_patch( patches.Circle((xd[interval], yd[interval]), radius_norm, facecolor="red")) ax1.text(xt[interval], yt[interval], pitch_classes[interval]) ax1.get_xaxis().set_visible(False) ax1.get_yaxis().set_visible(False) #plt.show() return ax1
def testFunctions(): ''' A sanity check function to test the capabilities of functions I made for the project. Right now it's set to test the magneticFieldAtPoint function, by plotting the magnetic field over a lattice of points. ''' plt = pyplot.figure(facecolor = 'w') ax = plt.add_subplot(111) ax.set_title("Preliminary Results") y = np.arange(-30000000, 30000000, 300000) z = np.arange(-30000000, 30000000, 300000) yy, zz = np.meshgrid(y, z) B = np.empty((y.size,z.size,3)) for i in range(y.size): for j in range(z.size): pt = np.array([0,yy[i,j],zz[i,j]]) B[i,j] = stepcalc.magneticFieldAtPoint(np.array([0,0,0]), pt, 1e14) #B[i,j] += np.array([2e-9,0,0]) B[int(y.size/2),int(z.size/2)] = np.array([0,0,0]) ax.quiver(yy,zz,B[:,:,1],B[:,:,2])#,scale = 5e3, scale_units = 'x') ax.set_title("Magnetic Field Lines from Dipole Cross Section") ax.set_xlabel("y (m)") ax.set_ylabel("z (m)") plt.show()
def draw(goalstate): # draw bounds fig, ax = plt.add_subplot() plt.plot([xmin, xmin, xmax, xmax, xmin], [ymin, ymax, ymax, ymin, ymin], color='k', lw=.5) # goal region goal = plt.Circle((E.xg, E.yg), radius=eg, color='g') ax.add_artist(goal) # draw tree G.showtree('0.45') # draw path print(goalstate) if goalstate < nmax + 1: G.showpath('r-') # draw obstacles for obstacle in obstacles: obs = plt.Circle((obstacle[0], obstacle[1]), radius=obstacle[2], color='k', fill=None) ax.add_artist(obs) plt.show()
# # `fig_3d.add_subplot(1,1,1,projection="3d")`) # # Since this visualization will be in 3D, we will need our third dimension. In this case, our `z` coordinate. # # Create a new variable `constellation3d` and call the scatter [function](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html) with your `x`, `y` and `z` coordinates. # # Include `z` just as you have been including the other two axes. (hint: `.scatter(x,y,z)`) # # Render your visualization. (hint `plt.show()`.) # # In[44]: plt.figure() plt.add_subplot(1, 1, 1, projection="3d") plt.scatter(x, y, z) plt.show() plt.savefig("fig_3d") # ## 5. Rotate and explore # # Use your mouse to click and drag the 3D visualization in the previous step. This will rotate the scatter plot. As you rotate, can you see Orion from different angles? # # Note: The on and off button that appears above the 3D scatter plot allows you to toggle rotation of your 3D visualization in your notebook. # # Take your time, rotate around! Remember, this will never look exactly like the Orion we see from Earth. The visualization does not curve as the night sky does. # There is beauty in the new understanding of Earthly perspective! We see the shape of the warrior Orion because of Earth's location in the universe and the location of the stars in that constellation. # # Feel free to map more stars by looking up other celestial x, y, z coordinates [here](http://www.stellar-database.com/). #
def run(self, tps, snap, data, para=None): plt = self.app.show_plot(para['title']) data[para['cn']].plot.pie(subplots=True, title=para['title'], ax=plt.add_subplot()) plt.Show()
return models #first process: /data/temp/ph290/last_1000 input_directory = '/media/usb_external1/cmip5/reynolds_data/past1000/' # tas variables = np.array(['sos']) experiments = ['past1000'] #specify the temperal averaging period of the data in your files e.g for an ocean file 'Omon' (Ocean monthly) or 'Oyr' (ocean yearly). Atmosphere would be comething like 'Amon'. Note this just prevents probvlems if you accidently did not specify the time frequency when doenloading the data, so avoids trying to puut (e.g.) daily data and monthly data in the same file. nao_file = '/home/ph290/data0/misc_data/nao-trouet2009.txt' nao = np.genfromtxt(nao_file,skip_header = 94) fig=plt.figure() ax1=plt.add_subplot(111) ax1.plot(data_final[:,0],data_final[:,1]) ax2 = ax1.twinx() ax2.plot(nao[:,0],nao[:,1]) plt.show() ''' #Main bit of code follows... ''' experiment = experiments[0] models = model_names(input_directory,variables[0],experiment) models = list(models) #models.remove('bcc-csm1-1')
# # Use the scatter [function](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html) to visualize your `x` and `y` coordinates. (hint: `.scatter(x,y)`) # # Render your visualization. (hint: `plt.show()`) # # Does the 2D visualization look like the Orion constellation we see in the night sky? Do you recognize its shape in 2D? There is a curve to the sky, and this is a flat visualization, but we will visualize it in 3D in the next step to get a better sense of the actual star positions. # In[39]: x = [-0.41, 0.57, 0.07, 0.00, -0.29, -0.32,-0.50,-0.23, -0.23] y = [4.12, 7.71, 2.36, 9.10, 13.35, 8.13, 7.19, 13.25,13.43] z = [2.06, 0.84, 1.56, 2.07, 2.36, 1.72, 0.66, 1.25,1.38] plt.figure() plt.add_subplot(1,1,1) plt.scatter(x,y) plt.show() # ## 4. Create a 3D Visualization # # Create a figure for the 3D plot and save it to a variable name `fig_3d`. (hint: `plt.figure()`) # # # Since this will be a 3D projection, we want to make to tell Matplotlib this will be a 3D plot. # # To add a 3D projection, you must include a the projection argument. It would look like this:
# 막대 그래프 활용하기 import pandas as pd import numpy as np from matplotlib import pyplot as plt df = pd.read_csv('C:\Temp\전염병발병현황_년도별_2.csv', encoding='euc-kr', index_col='년도') df.head(10) fig = plt.figure(figsize=(20, 10)) ax = plt.add_subplot(111) wt = np.array(range(len(df))) w = 0, 1 for i in df.colums: ax.bar(wt, df[i], width=w, label=i) wt = wt + w ax.set_xticks(np.array(range(len(df)))) ax.set_xticklabels(df.index, fontproperties=font) ax.set_xticklabels('발생건수', fontproperties=font) ax.legend() plt.show()
def apply_new_subplot(self): plt = self.figure if (self.plots_num == 1): plt.add_subplot(1, 1, 1) elif (self.plots_num == 2): plot_location = int('12' + str(len(self.plot_list) + 1)) plt.add_subplot(plot_location) elif (self.plots_num == 3): plot_location = int('13' + str(len(self.plot_list) + 1)) plt.add_subplot(plot_location) elif (self.plots_num == 4): plot_location = int('22' + str(len(self.plot_list) + 1)) plt.add_subplot(plot_location) elif (self.plots_num == 6): plot_location = int('23' + str(len(self.plot_list) + 1)) plt.add_subplot(plot_location) elif (self.plots_num == 9): plot_location = int('33' + str(len(self.plot_list) + 1)) plt.add_subplot(plot_location)
def _plot_image_overlay(self, f_pc, plot_component=None, peak_id=None, plot_char=None, plot_shifts=False, calibrate=True, img_cmap=plt.cm.gray, sc_cmap=plt.cm.jet, quiver_color='white', vector_scale=1, per_row=3, same_window=True, comp_label=None): """Overlays scores or some peak characteristic on top of an image plot of the original experimental image. Useful for obtaining a bird's-eye view of some image characteristic. plot_component - None or int (optional, but required to plot score overlays) The integer index of the component to plot scores for. Creates a scatter plot that is colormapped according to score values. peak_id - None or int (optional, but required to plot peak characteristic and shift overlays) If int, the peak id for plotting characteristics of. To identify peak id's, use the plot_peak_ids function, which will overlay the average image with the identified peaks used throughout the image series. plot_char - None or int (optional, but required to plot peak characteristic overlays) If int, the id of the characteristic to plot as the colored scatter plot. Possible components are: 4: peak height 5: peak orientation 6: peak eccentricity plot_shifts - bool, optional If True, plots shift overlays for given peak_id onto the parent image(s) """ smp = self.mapped_parameters if not hasattr(smp, "original_files"): messages.warning( """No original files available. Can't map anything to nothing. If you use the cell_cropper function to crop your cells, the cell locations and original files will be tracked for you.""") return None if peak_id is not None and (plot_shifts is False and plot_char is None): messages.warning( """Peak ID provided, but no plot_char given , and plot_shift disabled. Nothing to plot. Try again.""") return None keys = smp.original_files.keys() nfigs = len(keys) if nfigs < per_row: per_row = nfigs flist = [] if same_window: rows = int(np.ceil(nfigs / float(per_row))) f = plt.figure(figsize=(4 * per_row, 3 * rows)) for i in xrange(len(keys)): if same_window: ax = f.add_subplot(rows, per_row, i + 1) else: f = plt.figure() ax = plt.add_subplot(111) locs = smp.locations.copy() mask = locs['filename'] == keys[i] mask = mask.squeeze() # grab the array of peak locations, only from THIS image locs = locs[mask]['position'].squeeze() image = smp.original_files[keys[i]].data axes_manager = smp.original_files[keys[i]].axes_manager cbar_label = None if peak_id <> None: # add the offset for the desired peak so that it lies on top of the peak in the image. pk_loc = smp.peak_chars[:, mask][7 * peak_id:7 * peak_id + 2].T locs = locs + pk_loc if plot_char <> None: char = self._get_pk_char(f_pc[:, mask], locations=locs, plot_char=plot_char, peak_id=peak_id) id_label = peak_id if plot_char == 4: cbar_label = 'Peak Height' elif plot_char == 5: cbar_label = 'Peak Orientation' elif plot_char == 6: cbar_label = 'Peak Eccentricity' elif plot_component <> None: char = self._get_pk_char(f_pc[:, mask], locations=locs, plot_char=plot_char, comp_id=plot_component) id_label = plot_component cbar_label = 'Score' else: char = None if plot_shifts: shifts = self._get_pk_shifts(f_pc[:, mask], locations=locs) else: shifts = None if comp_label: label = comp_label + '%i:\n%s' % (id_label, keys[i]) else: label = keys[i] ax = sigdraw._plot_quiver_scatter_overlay(image=image, axes_manager=axes_manager, calibrate=calibrate, shifts=shifts, char=char, comp_label=label, img_cmap=img_cmap, sc_cmap=sc_cmap, quiver_color=quiver_color, ax=ax, vector_scale=vector_scale, cbar_label=cbar_label) if not same_window: flist.append(f) try: plt.tight_layout() except: pass if same_window: flist.append(f) return flist def plot_peak_overlay_cell(self, img_ids=None, calibrate=True, same_window=True, comp_label='img', plot_shifts=True, plot_char=None, quiver_color='white', vector_scale=1, cmap=plt.cm.jet, per_row=3): """Overlays peak characteristics on an image plot of the average image. Parameters ---------- img_ids : None, int, or list of ints if None, returns maps of average image. if int, returns maps of characteristics with ids from 0 to given int. if list of ints, returns maps of characteristics with ids in given list. calibrate : bool if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels. same_window : bool if True, plots each factor to the same window. They are not scaled. comp_label : string, the label that is either the plot title (if plotting in separate windows) or the label in the legend (if plotting in the same window) cmap : The colormap used for the factor image, or for peak characteristics, the colormap used for the scatter plot of some peak characteristic. per_row : int, the number of plots in each row, when the same_window parameter is True. plot_char - None or int (optional, but required to plot peak characteristic overlays) If int, the id of the characteristic to plot as the colored scatter plot. Possible components are: 0 or 1: peak coordinates 2 or 3: position difference relative to nearest target location 4: peak height 5: peak orientation 6: peak eccentricity plot_shift - bool, optional If True, plots shift overlays from the factor onto the image given in the cell_data parameter """ smp = self.mapped_parameters factors = smp.peak_chars #slice the images based on the img_ids if img_ids is not None: if not hasattr(img_ids, '__iter__'): img_ids = range(img_ids) mask = np.zeros(self.data.shape[0], dtype=np.bool) for idx in img_ids: mask[idx] = 1 img_data = self.data[mask] avg_char = False else: img_data = None avg_char = True return self._plot_factors_or_pchars(factors=factors, comp_ids=img_ids, calibrate=calibrate, comp_label=comp_label, img_data=img_data, avg_char=avg_char, on_peaks=True, plot_char=plot_char, plot_shifts=plot_shifts, cmap=cmap, quiver_color=quiver_color, vector_scale=vector_scale, per_row=per_row) def _plot_quiver_scatter_overlay(self, image, calibrate=True, shifts=None, char=None, ax=None, comp_label=None, img_cmap=plt.cm.gray, sc_cmap=plt.cm.jet, quiver_color='white', vector_scale=1, cbar_label=None): """quiver plot notes: The vector_scale parameter scales the quiver plot arrows. The vector is defined as one data unit along the X axis. If shifts are small, set vector_scale so that when they are multiplied by vector_scale, they are on the scale of the image plot. """ if ax == None: ax = plt.gca() extent = None if shifts is not None: slocs = shifts['location'].squeeze().copy() shifts = shifts['shift'].squeeze().copy() if char is not None: clocs = char['location'].squeeze().copy() """ if calibrate: extent=(axes[1].low_value, axes[1].high_value, axes[0].high_value, axes[0].low_value) if shifts is not None: slocs[:,0]=slocs[:,0]*axes[0].scale+axes[0].offset slocs[:,1]=slocs[:,1]*axes[1].scale+axes[1].offset shifts[:,0]=shifts[:,0]*axes[0].scale+axes[0].offset shifts[:,1]=shifts[:,1]*axes[1].scale+axes[1].offset if char is not None: clocs[:,0]=clocs[:,0]*axes[0].scale+axes[0].offset clocs[:,1]=clocs[:,1]*axes[1].scale+axes[1].offset """ ax.imshow(image, interpolation='nearest', cmap=img_cmap, extent=extent) if comp_label: plt.title(comp_label) if shifts is not None: ax.quiver(slocs[:, 0], slocs[:, 1], shifts[:, 0], shifts[:, 1], units='x', color=quiver_color, scale=vector_scale, scale_units='x') if char is not None: sc = ax.scatter(clocs[:, 0], clocs[:, 1], c=char['char'], cmap=sc_cmap) div = make_axes_locatable(ax) cax = div.append_axes('right', size="5%", pad=0.05) cb = plt.colorbar(sc, cax=cax) if cbar_label: cb.set_label(cbar_label) if extent: ax.set_xlim(extent[:2]) ax.set_ylim(extent[2:]) else: ax.set_xlim(0, image.shape[0]) ax.set_ylim(image.shape[1], 0) return ax def plot_image_peaks(img_data, locations, plot_ids=False, ax=None): if ax is None: ax = plt.gca() ax.imshow(img_data, cmap=plt.gray(), interpolation='nearest') if plot_ids: for pk_id in xrange(locations.shape[0]): plt.text(locations[pk_id, 0], locations[pk_id, 1], "%s" % pk_id, size=10, rotation=0., ha="center", va="center", bbox=dict( boxstyle="round", ec=(1., 0.5, 0.5), fc=(1., 0.8, 0.8), )) else: ax.scatter(locations[:, 0], locations[:, 1]) ax.set_xlim(0, img_data.shape[0] - 1) ax.set_ylim(img_data.shape[1] - 1, 0) return ax
def _plot_image_overlay(self,f_pc, plot_component=None, peak_id=None, plot_char=None, plot_shifts=False,calibrate=True, img_cmap=plt.cm.gray, sc_cmap=plt.cm.jet, quiver_color='white',vector_scale=1, per_row=3,same_window=True, comp_label=None): """Overlays scores or some peak characteristic on top of an image plot of the original experimental image. Useful for obtaining a bird's-eye view of some image characteristic. plot_component - None or int (optional, but required to plot score overlays) The integer index of the component to plot scores for. Creates a scatter plot that is colormapped according to score values. peak_id - None or int (optional, but required to plot peak characteristic and shift overlays) If int, the peak id for plotting characteristics of. To identify peak id's, use the plot_peak_ids function, which will overlay the average image with the identified peaks used throughout the image series. plot_char - None or int (optional, but required to plot peak characteristic overlays) If int, the id of the characteristic to plot as the colored scatter plot. Possible components are: 4: peak height 5: peak orientation 6: peak eccentricity plot_shifts - bool, optional If True, plots shift overlays for given peak_id onto the parent image(s) """ smp=self.mapped_parameters if not hasattr(smp, "original_files"): messages.warning("""No original files available. Can't map anything to nothing. If you use the cell_cropper function to crop your cells, the cell locations and original files will be tracked for you.""") return None if peak_id is not None and (plot_shifts is False and plot_char is None): messages.warning("""Peak ID provided, but no plot_char given , and plot_shift disabled. Nothing to plot. Try again.""") return None keys=smp.original_files.keys() nfigs=len(keys) if nfigs<per_row: per_row=nfigs flist=[] if same_window: rows=int(np.ceil(nfigs/float(per_row))) f=plt.figure(figsize=(4*per_row,3*rows)) for i in xrange(len(keys)): if same_window: ax=f.add_subplot(rows,per_row,i+1) else: f=plt.figure() ax=plt.add_subplot(111) locs=smp.locations.copy() mask=locs['filename']==keys[i] mask=mask.squeeze() # grab the array of peak locations, only from THIS image locs=locs[mask]['position'].squeeze() image=smp.original_files[keys[i]].data axes_manager=smp.original_files[keys[i]].axes_manager cbar_label=None if peak_id<>None: # add the offset for the desired peak so that it lies on top of the peak in the image. pk_loc=smp.peak_chars[:,mask][7*peak_id:7*peak_id+2].T locs=locs+pk_loc if plot_char<>None: char=self._get_pk_char(f_pc[:,mask], locations=locs, plot_char=plot_char, peak_id=peak_id) id_label=peak_id if plot_char==4: cbar_label='Peak Height' elif plot_char==5: cbar_label='Peak Orientation' elif plot_char==6: cbar_label='Peak Eccentricity' elif plot_component<>None: char=self._get_pk_char(f_pc[:,mask], locations=locs, plot_char=plot_char, comp_id=plot_component) id_label=plot_component cbar_label='Score' else: char=None if plot_shifts: shifts=self._get_pk_shifts(f_pc[:,mask], locations=locs) else: shifts=None if comp_label: label=comp_label+'%i:\n%s'%(id_label,keys[i]) else: label=keys[i] ax=sigdraw._plot_quiver_scatter_overlay(image=image, axes_manager=axes_manager, calibrate=calibrate, shifts=shifts, char=char, comp_label=label, img_cmap=img_cmap, sc_cmap=sc_cmap, quiver_color=quiver_color,ax=ax, vector_scale=vector_scale, cbar_label=cbar_label) if not same_window: flist.append(f) try: plt.tight_layout() except: pass if same_window: flist.append(f) return flist def plot_peak_overlay_cell(self, img_ids=None, calibrate=True, same_window=True, comp_label='img', plot_shifts=True, plot_char=None, quiver_color='white', vector_scale=1, cmap=plt.cm.jet, per_row=3): """Overlays peak characteristics on an image plot of the average image. Parameters ---------- img_ids : None, int, or list of ints if None, returns maps of average image. if int, returns maps of characteristics with ids from 0 to given int. if list of ints, returns maps of characteristics with ids in given list. calibrate : bool if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels. same_window : bool if True, plots each factor to the same window. They are not scaled. comp_label : string, the label that is either the plot title (if plotting in separate windows) or the label in the legend (if plotting in the same window) cmap : The colormap used for the factor image, or for peak characteristics, the colormap used for the scatter plot of some peak characteristic. per_row : int, the number of plots in each row, when the same_window parameter is True. plot_char - None or int (optional, but required to plot peak characteristic overlays) If int, the id of the characteristic to plot as the colored scatter plot. Possible components are: 0 or 1: peak coordinates 2 or 3: position difference relative to nearest target location 4: peak height 5: peak orientation 6: peak eccentricity plot_shift - bool, optional If True, plots shift overlays from the factor onto the image given in the cell_data parameter """ smp=self.mapped_parameters factors=smp.peak_chars #slice the images based on the img_ids if img_ids is not None: if not hasattr(img_ids,'__iter__'): img_ids=range(img_ids) mask=np.zeros(self.data.shape[0],dtype=np.bool) for idx in img_ids: mask[idx]=1 img_data=self.data[mask] avg_char=False else: img_data=None avg_char=True return self._plot_factors_or_pchars(factors=factors, comp_ids=img_ids, calibrate=calibrate, comp_label=comp_label, img_data=img_data,avg_char=avg_char, on_peaks=True, plot_char=plot_char, plot_shifts=plot_shifts, cmap=cmap, quiver_color=quiver_color, vector_scale=vector_scale, per_row=per_row) def _plot_quiver_scatter_overlay(self, image, calibrate=True, shifts=None, char=None, ax=None, comp_label=None, img_cmap=plt.cm.gray, sc_cmap=plt.cm.jet, quiver_color='white', vector_scale=1, cbar_label=None ): """quiver plot notes: The vector_scale parameter scales the quiver plot arrows. The vector is defined as one data unit along the X axis. If shifts are small, set vector_scale so that when they are multiplied by vector_scale, they are on the scale of the image plot. """ if ax==None: ax=plt.gca() extent=None if shifts is not None: slocs=shifts['location'].squeeze().copy() shifts=shifts['shift'].squeeze().copy() if char is not None: clocs=char['location'].squeeze().copy() """ if calibrate: extent=(axes[1].low_value, axes[1].high_value, axes[0].high_value, axes[0].low_value) if shifts is not None: slocs[:,0]=slocs[:,0]*axes[0].scale+axes[0].offset slocs[:,1]=slocs[:,1]*axes[1].scale+axes[1].offset shifts[:,0]=shifts[:,0]*axes[0].scale+axes[0].offset shifts[:,1]=shifts[:,1]*axes[1].scale+axes[1].offset if char is not None: clocs[:,0]=clocs[:,0]*axes[0].scale+axes[0].offset clocs[:,1]=clocs[:,1]*axes[1].scale+axes[1].offset """ ax.imshow(image,interpolation='nearest', cmap=img_cmap,extent=extent) if comp_label: plt.title(comp_label) if shifts is not None: ax.quiver(slocs[:,0],slocs[:,1], shifts[:,0], shifts[:,1], units='x',color=quiver_color, scale=vector_scale, scale_units='x') if char is not None: sc=ax.scatter(clocs[:,0],clocs[:,1], c=char['char'], cmap=sc_cmap) div=make_axes_locatable(ax) cax=div.append_axes('right',size="5%",pad=0.05) cb=plt.colorbar(sc,cax=cax) if cbar_label: cb.set_label(cbar_label) if extent: ax.set_xlim(extent[:2]) ax.set_ylim(extent[2:]) else: ax.set_xlim(0,image.shape[0]) ax.set_ylim(image.shape[1],0) return ax def plot_image_peaks(img_data, locations, plot_ids=False, ax=None): if ax is None: ax=plt.gca() ax.imshow(img_data,cmap=plt.gray(), interpolation = 'nearest') if plot_ids: for pk_id in xrange(locations.shape[0]): plt.text(locations[pk_id,0], locations[pk_id,1], "%s"%pk_id, size=10, rotation=0., ha="center", va="center", bbox = dict(boxstyle="round", ec=(1., 0.5, 0.5), fc=(1., 0.8, 0.8), ) ) else: ax.scatter(locations[:,0],locations[:,1]) ax.set_xlim(0,img_data.shape[0]-1) ax.set_ylim(img_data.shape[1]-1,0) return ax