def draw(self): circle = pyplot.Circle((self.x, self.y), radius=neuron_radius, color=self.color,alpha=alpha) pyplot.gca().add_patch(circle)
ax = plt.axes() camera = Camera(fig) steps = 10 # simulation steps for step in range(steps): # the appearance of bacteria and nutrient on the map ax.scatter(x=[i.bac_coord.x for i in bacterias_list], y=[j.bac_coord.y for j in bacterias_list], c=[dict_color[k.is_resistant] for k in bacterias_list], marker='o') ax.scatter(x=[i.coord.x for i in food], y=[j.coord.y for j in food], c="green", marker='o', s=10) # if it's time an enlarging antibiotic zone appears if (step in antibiotic_time_1) or (step in antibiotic_time_2) or (step in antibiotic_time_3): r = antibiotic_r[r_num] ax.add_artist(plt.Circle((0, 0), r, color="k", alpha=0.3)) r_num += 1 else: r_num = 0 camera.snap() resist_sum = 0 # at each step we count how many bacteria with and without a plasmid, in order to build a graph for check in bacterias_list: if check.is_resistant: resist_sum += 1 resist.append(resist_sum) sensitive.append(len(bacterias_list) - resist_sum) for bacteria in bacterias_list:
def plotSpotsOnWholeImage(path_to_spotsCSV: str, tile_grid_shape: Tuple[int, int], tile_size_x: int, tile_size_y: int, path_to_original_img=""): """Takes a csv of spots as calculated by spotDetection.py and plots them on an untiled empty canvas that has the size of the original image. Parameters ---------- path_to_spotsCSV : str Path to input csv file that contains the spots. They should include the following columns, spelled as such: 'Tile', 'X', 'Y', 'Sigma' tile_grid_shape : tuple Tuple of ints containing the x and y size of the original image (in that order). eg.: (1330, 980) tile_size_x : int Number of columns in the tiled images, or the size of the X-axis. tile_size_y : int Number of rows in the tiled images, or the size of the Y-axis. path_to_img : str, optional Path to input image of which the spots originate """ # Parse input df = pd.read_csv(path_to_spotsCSV) # Calculate tile grid properties: total_n_tiles, tile_grid_array, original_x, original_y = calculateTileGridStatistics( tile_grid_shape, tile_size_x, tile_size_y) # Create empty image size of the original image empty_image = np.zeros((original_y, original_x)) if path_to_original_img: fig, axs = plt.subplots(1, 2) image = io.imread(path_to_original_img) axs[0].imshow(image) axs[0].set_title('Original image') axs[1].imshow(empty_image) axs[1].set_title("Detected spots") for row in df.itertuples(): # extract X and Y coordinates of the respective tile the spot belongs to row_location, col_location = np.where( tile_grid_array == row.Tile ) # this returns rows and columns, NOT X and Y, which is the opposite # unpacking the array structure of the return tuple of np.where y_tile_location, x_tile_location = row_location[0], col_location[0] # Calculate how many pixels to add in order to plot the spot in the correct tile in the original image x_adder = x_tile_location * tile_size_x y_adder = y_tile_location * tile_size_y # Calculate the position in the original image x_coordinate = row.X + x_adder y_coordinate = row.Y + y_adder circ = plt.Circle((x_coordinate, y_coordinate), radius=2) axs[1].add_patch(circ) for ax in axs: ax.set(xlabel='X-coordinates', ylabel='y-coordinates') else: fig, ax = plt.subplots(1, 1) ax.imshow(empty_image, cmap='gray') for row in df.itertuples(): # extract X and Y coordinates of the respective tile the spot belongs to row_location, col_location = np.where( tile_grid_array == row.Tile ) # this returns rows and columns, NOT X and Y, which is the opposite # unpacking the array structure of the return tuple of np.where y_tile_location, x_tile_location = row_location[0], col_location[0] # Calculate how many pixels to add in order to plot the spot in the correct tile in the original image x_adder = x_tile_location * tile_size_x y_adder = y_tile_location * tile_size_y # Calculate the position in the original image x_coordinate = row.X + x_adder y_coordinate = row.Y + y_adder circ = plt.Circle((x_coordinate, y_coordinate), radius=2) ax.add_patch(circ) fig.tight_layout() plt.axis('off') plt.savefig("detected_spots_plotted.pdf")
def plot_frame(index, spin, massfrac, count, doplot=True): cachename = "cache/frame_{0:05d}.h5".format(index) loaded = False try: if os.path.exists(cachename): hfp = h5py.File(cachename, 'r') if hfp['spin'][()] == spin and hfp['massfrac'][ ()] == massfrac and hfp['count'][()] == count: loaded = True hfp.close() except: pass if not loaded or "--overwritec" in sys.argv: xs, ys, xes, yes = get_rays_for_spin_mass(spin, massfrac, count) hfp = h5py.File(cachename, 'w') hfp['spin'] = spin hfp['massfrac'] = massfrac hfp['count'] = count for i in range(count): hfp[f'xs_{i}'] = xs[i] hfp[f'ys_{i}'] = ys[i] for i in range(4): hfp[f'xes_{i}'] = xes[i] hfp[f'yes_{i}'] = yes[i] hfp.close() hfp = h5py.File(cachename, 'r') xs = [] ys = [] for i in range(count): xs.append(np.array(hfp[f'xs_{i}'])) ys.append(np.array(hfp[f'ys_{i}'])) xes = [ np.array(hfp['xes_0']), np.array(hfp['xes_1']), np.array(hfp['xes_2']), np.array(hfp['xes_3']) ] yes = [ np.array(hfp['yes_0']), np.array(hfp['yes_1']), np.array(hfp['yes_2']), np.array(hfp['yes_3']) ] hfp.close() if doplot: # create figure plt.close('all') fig = plt.figure(figsize=(8, 9), facecolor=bgcolor) ax1 = plt.subplot(1, 1, 1) for i, x in enumerate(xs): y = ys[i] r = x * x + y * y color = color_inf zorder = 10 if r[-1] < 20: color = color_hit zorder = 20 ax1.plot(y, -x, lw=1, c=color, zorder=zorder) # left black boundary plot_background_above(yes[1], -xes[1], dark_bgcolor, ax1) # right black boundary plot_background_above(yes[3], -xes[3], dark_bgcolor, ax1) if index < 4: plot_reds_pre(yes[1], -xes[1], yes[3], -xes[3], '#000', ax1) orient_up = False if index < 230: plot_reds_pre(yes[0], -xes[0], yes[2], -xes[2], hit_bgcolor, ax1) else: plot_background_above(yes[0], -xes[0], hit_bgcolor, ax1, offset=3) plot_background_above(yes[2], -xes[2], hit_bgcolor, ax1, offset=3) if index > 300: plot_other_blob(yes[2], -xes[2], hit_bgcolor, ax1) # add black hole for style radius_eh = 1. + np.sqrt(1. - spin * spin) * 1.05 bh = plt.Circle((0, 0), radius_eh, color='#aaa', zorder=100) ax1.add_artist(bh) # format plot tlim = 15 ax1.set_xlim(-tlim, tlim) ax1.set_ylim(-tlim, tlim) ax1.set_aspect('equal') plt.tight_layout(rect=[0, -0.1, 1, 0.8]) ax1.set_facecolor(face_bgcolor) ax1.spines['bottom'].set_color(acolor) ax1.spines['left'].set_color(acolor) ax1.spines['left'].set_visible(False) ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.tick_params(axis='x', colors=acolor) ax1.tick_params(axis='y', colors=acolor) ax1.tick_params(axis='x', labelsize=22) ax1.tick_params(axis='y', labelsize=22) ax1.set_yticklabels([]) ax1.set_yticks([]) fig.text(0.13, 0.955, "GR", fontsize=32, ha='right', va='center') draw_progress_bar(fig, 0.15, 0.94, 0.45, 0.98, massfrac) fig.text(0.58, 0.955, "spin", fontsize=32, ha='right', va='center') draw_progress_bar(fig, 0.6, 0.94, 0.96, 0.98, spin) plt.tight_layout(rect=[0, 0, 1, 1]) if nobg: plt.savefig("imgs/frame_{0:05d}_{1:04d}.png".format(index, ogfade)) else: plt.savefig("imgs/frame_{0:05d}.png".format(index))
def drawCircle(self): plt.gca().add_patch( plt.Circle((0, 0), radius=self.radius, fc=self.color)) plt.axis('scaled') plt.show()
norm_2niso_min, norm_2niso_max = np.amin(norm_2niso), np.amax(norm_2niso) print("norm_2iso_min: ", norm_2iso_min, ", norm_2iso_max: ", norm_2iso_max) print("norm_2niso_min: ", norm_2niso_min, ", norm_2niso_max: ", norm_2niso_max) norm_2iso_lin = ((norm_2iso - norm_2iso_min) / ((norm_2iso_max - norm_2iso_min) / n_q_lin)) norm_2niso_lin = ((norm_2niso - norm_2niso_min) / ((norm_2niso_max - norm_2niso_min) / n_q_lin)) # need to manually select the radius # print(gibbs_rad['G=' + str(G)]['B2F6']['P4Iso=' + 'Yes']['droplet']) sim_2iso_rad = gibbs_rad['G=' + str(G)]['B2F6']['P4Iso=' + 'Yes']['droplet'][0] sim_2niso_rad = gibbs_rad['G=' + str(G)]['B2F6']['P4Iso=' + 'No']['droplet'][0] circle_2iso = plt.Circle((LX // 2, LX // 2), sim_2iso_rad, color='black', fill=False) circle_2niso = plt.Circle((LX // 2, LX // 2), sim_2niso_rad, color='black', fill=False) for x in range(norm_2iso_lin.shape[0]): for y in range(norm_2iso_lin.shape[1]): norm_2iso_lin[(x, y)] = int((norm_2iso_lin[(x, y)])) for x in range(norm_2niso_lin.shape[0]): for y in range(norm_2niso_lin.shape[1]): norm_2niso_lin[(x, y)] = int(norm_2niso_lin[(x, y)]) f_s = 16
def plot_2d_n_sets(sets, circles=[], labels=[], xlabel='x', ylabel='y', axis='xy', x_range=[0.0, 1.0], y_range=[0.0, 1.0], plot_type='lines', show_legend=True, idx=None, lw=5, linestyles=[], color_map=[], save=False, path="", filename="emd.png"): ps = [] if len(labels) != len(sets): labels = ['default' for i in xrange(len(sets))] if len(color_map) == 0: color_map = ['#000000' for i in xrange(len(sets))] if len(linestyles) == 0: linestyles = ['solid' for i in xrange(len(sets))] fig = plt.figure() ax = plt.subplot(111) if plot_type == 'lines': for i in xrange(len(sets)): try: ax.errorbar(sets[i][:, 0], sets[i][:, 1], yerr=sets[i][:, 2], color=color_map[i], label=labels[i], linewidth=lw, linestyle=linestyles[i]) except Exception as e: print e ax.errorbar(sets[i][:, 0], sets[i][:, 1], color=color_map[i], label=labels[i], linewidth=lw, linestyle=linestyles[i]) else: ax = fig.add_subplot(111) for i in xrange(len(sets)): ax.scatter(sets[i][:, 0], sets[i][:, 1], c=np.random.rand(3, 1), label=labels[i], s=13) if show_legend: plt.legend(loc='upper left') for circle in circles: ax = fig.add_subplot(111) circ = plt.Circle((circle[0], circle[1]), radius=circle[2], color='g', fill=True) ax.add_patch(circ) if show_legend: box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(loc='upper left', bbox_to_anchor=(1, 1)) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.xlim([x_range[0], x_range[1]]) plt.ylim([y_range[0], y_range[1]]) plt.xticks(np.arange(x_range[0], x_range[1], 5.0)) if save: for file in glob.glob(os.path.join(path, filename)): os.remove(file) plt.savefig(os.path.join(path, filename)) plt.clf() return plt.show() plt.clf()
axes[1].plot(means_left[:, 0], color="black", alpha=1.0) axes[2].plot(means_left[:, 1], color="black", alpha=1.0) axes[3].plot(means_left[:, 0], means_left[:, 1], color="black", alpha=1.0) # axes[3].plot(reconstr_traj_mean_left_x[:], reconstr_traj_mean_left_y[:], color="red", alpha = 1.0) circles_right = [] circles_right_x = [] circles_right_y = [] circles_straight = [] circles_straight_x = [] circles_straight_y = [] circles_left = [] circles_left_x = [] circles_left_y = [] for i in range(time_steps): circle_right = plt.Circle((means_right[i][0], means_right[i][1]), radius=2 * np.linalg.norm(std_right[i])) circle_straight = plt.Circle((means_straight[i][0], means_straight[i][1]), radius=2 * np.linalg.norm(std_straight[i])) circle_left = plt.Circle((means_left[i][0], means_left[i][1]), radius=2 * np.linalg.norm(std_left[i])) # 1*std --> 68.27%, 2*std --> 95.45%, 3*std --> 99.73%. circle_right_x = plt.Circle((i, means_right[i][0]), radius=2 * np.linalg.norm(std_right[i])) circle_right_y = plt.Circle((i, means_right[i][1]), radius=2 * np.linalg.norm(std_right[i])) circle_straight_x = plt.Circle((i, means_straight[i][0]), radius=2 * np.linalg.norm(std_straight[i])) circle_straight_y = plt.Circle((i, means_straight[i][1]), radius=2 * np.linalg.norm(std_straight[i])) circle_left_x = plt.Circle((i, means_left[i][0]), radius=2 * np.linalg.norm(std_left[i]))
np.sin(theta[i]) * wall for i in range(theta.size)]) ax_swr_x = np.array([ax_sw_x[i] - np.sign(theta[i] - np.pi) * np.cos(theta[i]) * wall for i in range(theta.size)]) ax_swr_y = np.array([ax_sw_y[i] + np.sign(theta[i] - np.pi) * np.sin(theta[i]) * wall for i in range(theta.size)]) if not n % 2: # With a pair number of cylinders, the bottom ones are ax_swl_x[n // 2 - 1] = ax_pwl_x # problematic, so they're ax_swl_y[n // 2 - 1] = -ax_pw_y # recalculated here. ax_swr_x[n // 2 - 1] = ax_pwr_x ax_swr_y[n // 2 - 1] = -ax_pw_y # Plotting crankcase. case = plt.Circle([0., 0.], c_radius, facecolor='white', edgecolor='black', linewidth=2) ax1.add_patch(case) # White rectangles painted over crankcase as the cylinder insides. wp = plt.Rectangle([-wall, 0.], PW + 2. * space, t_radius, color='white') ws = [plt.Rectangle([-wall, 0.], PW + 2. * space, t_radius, color='white') for i in range(theta.size)] ts = [mpl.transforms.Affine2D().rotate(-theta[i]) + ax1.transData for i in range(theta.size)] ax1.add_patch(wp) for i in range(theta.size): ws[i].set_transform(ts[i]) ax1.add_patch(ws[i]) # Plotting cylinders axis. ax1.plot(ax_p_x, ax_p_y, '--', color='gray')
# x, y = np.random.normal(size=(2, 100)) ax1.plot(x, y, 'o') # x = np.arange(0, 10) y = np.arange(0, 10) ncolors = len(plt.rcParams['axes.color_cycle']) # how many colors in plt shift = np.linspace(0, 10, ncolors) for s in shift: ax2.plot(x, y + s, '-') # bar chart x = np.arange(5) y1, y2, y3 = np.random.randint(1, 25, size=(3, 5)) width = 0.25 ax3.bar(x, y1, width) ax3.bar(x + width, y2, width) ax3.bar(x + 2 * width, y3, width) # for i, color in enumerate(plt.rcParams['axes.color_cycle']): xy = np.random.normal(size=2) ax4.add_patch(plt.Circle(xy, radius=0.3, color=color)) ax4.axis('equal') plt.show()
self.vely = -1 * self.vely if self.y <= 0: self.y = 0 self.vely = -1 * self.vely # Initializing dots dots = [dot() for i in xrange(N)] # First set up the figure, the axis, and the plot element we want to animate fig = plt.figure() ax = plt.axes(xlim=(0, 10), ylim=(0, 10)) d, = ax.plot([dot.x for dot in dots], [dot.y for dot in dots], 'ro') #adds a static circle to the grap circle = plt.Circle((5, 5), 1, color='b', fill=False) ax.add_artist(circle) # animation function. This is called sequentially def animate(i): for dot in dots: dot.move() d.set_data([dot.x for dot in dots], [dot.y for dot in dots]) print(d) return d, # call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(fig, animate, frames=200, interval=20)
for i in range(20,2,-1): x = wbr['cnt'] plt.hist(x, bins=i) plt.show() print(i) #Dibujar ax = plt.subplots(figsize=(9, 9)) #Define plot size ax = plt.gca() #Create emty plot # change default range so that new circles will work ax.set_xlim((0, 10)) ax.set_ylim((0, 10)) c1=plt.Circle((5, 5), 1, alpha=1, color='r') #Define circle (coordenadas x e y, radio, transparencia y color) ax.add_artist(c1) #Draw circle #Con bucle for para poner todos los círculos en la diagonal principal ax = plt.subplots(figsize=(9, 9)) #Define plot size ax = plt.gca() #Create emty plot # change default range so that new circles will work ax.set_xlim((0, 10)) ax.set_ylim((0, 10)) for i in range(0,11,1): c1=plt.Circle((i, i), 0.5, alpha=1, color='r') ax.add_artist(c1) #Con "animación" ax = plt.subplots(figsize=(9, 9)) #Define plot size
def plot_square_farm(turbineX, turbineY, rotor_diameter, boundary_x, boundary_y, boundary_width, min_spacing=2, save_start=False, show_start=False, save_file=None): full_bound_x = np.array([ boundary_x[0], boundary_x[0], boundary_x[1], boundary_x[1], boundary_x[0] ]) full_bound_y = np.array([ boundary_y[0], boundary_y[1], boundary_y[1], boundary_y[0], boundary_y[0] ]) real_bound_x = np.array([ boundary_x[0] + rotor_diameter / 2., boundary_x[0] + rotor_diameter / 2., boundary_x[1] - rotor_diameter / 2., boundary_x[1] - rotor_diameter / 2., boundary_x[0] + rotor_diameter / 2. ]) real_bound_y = np.array([ boundary_y[0] + rotor_diameter / 2., boundary_y[1] - rotor_diameter / 2., boundary_y[1] - rotor_diameter / 2., boundary_y[0] + rotor_diameter / 2., boundary_y[0] + rotor_diameter / 2. ]) fig, ax = plt.subplots() for x, y in zip(turbineX / rotor_diameter, turbineY / rotor_diameter): # print("here") circle_start = plt.Circle((x, y), 0.5, facecolor='none', edgecolor='r', linestyle='-', label='Start') ax.add_artist(circle_start) ax.plot(full_bound_x / rotor_diameter, full_bound_y / rotor_diameter) ax.plot(real_bound_x / rotor_diameter, real_bound_y / rotor_diameter, '--') # ax.plot(turbineX / rotor_diameter, turbineY / rotor_diameter, 'sk', label='Original', mfc=None) # ax.plot(prob['turbineX'] / rotor_diameter, prob['turbineY'] / rotor_diameter, '^g', label='Optimized', mfc=None) # ax.add_patch(boundary_circle) plt.axis('equal') # ax.legend([circle_start], ['turbines']) ax.set_xlabel('Turbine X Position ($X/D_r$)') ax.set_ylabel('Turbine Y Position ($Y/D_r$)') if save_start: if save_file is None: plt.savefig('round_farm_%iTurbines_%0.2fDSpacing.pdf' % (turbineX.size, min_spacing)) else: plt.savefig(save_file) if show_start: plt.show()
import numpy as np from matplotlib.animation import ArtistAnimation #fig = plt.figure() x = np.arange(5,6.3,0.1) y = 1*(x-4.4)**2+1*(x-4.4)+4 plt.plot(x,y,'b') plt.plot([5.3,9], [11.8,1],'b') plt.plot([3.8,8.6], [2.8,11.8],'y--') circle1 = plt.Circle((3,8), 2, color='m', fill=False) ax=plt.gca() ax.add_patch(circle1) plt.axis('scaled') circle2 = plt.Circle((3,2), 1, color='c', fill=False) ax=plt.gca() ax.add_patch(circle2) plt.axis('scaled') plt.plot([4,4.7,5,5.2,5.8,5.3,5,4.6,4], [12,12.5,13,12.5,12,11.8,11.3,11.9,12])
def diff_plot(filename, idcs, setname='centered', beamdiam=100e-9, rings=(10, 5, 2.5), radii=(3, 4, 6), show_map=True, show_peaks=True, show_predict=False, figsize=(15, 10), dpi=300, cutoff=99.5, width=616, xoff=0, yoff=0, ellipticity=0, map_px=None, clen=None, det_px=None, wavelength=None, stacks=None, shots=None, peaks=None, predict=None, base_path='/%/data', map_path='/%/map/image', results_path='/%/results', pre_compute=True, store_to=None, cmap='gray', ringcolor='y', **kwargs): """ """ if shots is None: shots = get_meta_lists(filename, base_path, ['shots'])['shots'] if show_peaks and peaks is None: peaks = get_meta_lists(filename, results_path, ['peaks'])['peaks'] if show_predict and predict is None: predict = get_meta_lists(filename, results_path, ['predict'])['predict'] if stacks is None: stacks = get_data_stacks(filename, base_path, [setname]) # TODO: replace all the following defaults by proper reading from NeXus and assigning to shots shotsel = shots.loc[idcs, :].copy() if map_px is None: map_px = shotsel['map_px'] = 17e-9 else: shotsel['map_px'] = map_px if clen is None: shotsel['clen'] = 1.57 else: shotsel['clen'] = clen if det_px is None: shotsel['det_px'] = 55e-6 else: shotsel['det_px'] = det_px if wavelength is None: shotsel['wavelength'] = 2.5e-12 else: shotsel['wavelength'] = wavelength shotsel['recpx'] = shotsel['wavelength'] / (shotsel['det_px'] / shotsel['clen']) * 1e10 imgs = stacks[setname][shotsel.index.values, ...] if pre_compute: imgs = imgs.compute() if show_map: map_path = map_path.replace('%', 'entry') map_imgs = meta_from_nxs(list(shotsel['file'].unique()), map_path)[map_path] figs = [] for ii, ((idx, shot), img) in enumerate(zip(shotsel.iterrows(), imgs)): if not pre_compute: img = img.compute() figh = plt.figure(figsize=figsize, dpi=dpi, **kwargs) figs.append(figh) #figh = figs[ii] img_ax = figh.add_axes([0, 0, 0.66, 0.95]) img_ax.imshow(img, vmin=0, vmax=np.quantile(img, cutoff/100), cmap=cmap, label='diff') if show_peaks: coords = peaks.loc[peaks['serial'] == idx, :] else: coords = pd.DataFrame() if show_predict: pred_coords = peaks.loc[predict['serial'] == idx, :] else: pred_coords = pd.DataFrame() img_ax.set_xlim((778 - width/2, 778 + width/2)) try: img_ax.set_title( 'Set: {}, Shot: {}, Region: {}, Run: {}, Frame: {} \n (#{} in file: {}) PEAKS: {}'.format(shot['subset'], idx, shot['region'], shot['run'], shot['frame'], shot['shot'], shot['file'], len(coords), 3)) except: 'Shot {}: (file: {}) PEAKS: {}'.format(shot['subset'], shot['file'], len(coords), 3) #print(shot['recpx']) for res in rings: img_ax.add_artist(mpl.patches.Ellipse((img.shape[1] / 2 + xoff, img.shape[0] / 2 + yoff), width=2*(shot['recpx'] / res), height=2*(shot['recpx'] / res * (1+ellipticity)), edgecolor=ringcolor, fill=False)) img_ax.text(img.shape[1] / 2 + shot['recpx'] / res / 1.4, img.shape[0] / 2 - shot['recpx'] / res / 1.4, '{} A'.format(res), color=ringcolor) for _, c in coords.iterrows(): img_ax.add_artist(plt.Circle((c['fs/px'] - 0.5, c['ss/px'] - 0.5), radius=radii[0], fill=True, color='r', alpha=0.15)) img_ax.add_artist(plt.Circle((c['fs/px'] - 0.5, c['ss/px'] - 0.5), radius=radii[1], fill=False, color='y', alpha=0.2)) img_ax.add_artist(plt.Circle((c['fs/px'] - 0.5, c['ss/px'] - 0.5), radius=radii[2], fill=False, color='y', alpha=0.3)) for _, c in pred_coords.iterrows(): img_ax.add_artist(plt.Rectangle((c['fs/px'] - 0.5, c['ss/px'] - 0.5), width=radii[-1], height=radii[-1], fill=False, color='b')) img_ax.axis('off') if not show_map: continue #map_px = shotsel['map_px'] #print(map_px) map_ax = figh.add_axes([0.6, 0.5, 0.45, 0.45]) feat_ax = figh.add_axes([0.6, 0, 0.45, 0.45]) map_ax.imshow(map_imgs[shot['file']], cmap='gray') map_ax.add_artist(plt.Circle((shot['crystal_x'], shot['crystal_y']), facecolor='r')) map_ax.add_artist(AnchoredSizeBar(map_ax.transData, 5e-6 / map_px, '5 um', 'lower right')) map_ax.axis('off') feat_ax.imshow(map_imgs[shot['file']], cmap='gray') #feat_ax.add_artist(AnchoredSizeBar(feat_ax.transData, 0.1e-6 / map_px, '100 nm', 'lower right')) feat_ax.add_artist(plt.Circle((shot['crystal_x'], shot['crystal_y']), radius=beamdiam/2/map_px, color='r', fill=False)) if not np.isnan(shot['crystal_x']): feat_ax.set_xlim(shot['crystal_x'] + np.array([-20, 20])) feat_ax.set_ylim(shot['crystal_y'] + np.array([-20, 20])) else: feat_ax.set_xlim(shot['pos_x'] + np.array([-20, 20])) feat_ax.set_ylim(shot['pos_y'] + np.array([-20, 20])) feat_ax.axis('off') if store_to is not None: plt.savefig('{}/{}_{:04d}'.format(store_to, filename.rsplit('.', 1)[0].rsplit('/', 1)[-1], idx)) plt.close(plt.gcf()) return figs
# %% Sample use of ColorMap2, longer # Set-up canvas fig = plt.figure(figsize=(7.5, 9)) ax = fig.add_axes([0, 0.2, 1, 0.8]) cax = fig.add_axes([0.6, 0, 0.4, 0.3]) fig.suptitle('color of circle based on x-coordinate and y-coordinate') # Set-up colormap cmap = p2c.ColorMap2(['#7A11D8', '#9935F3'], ['#2FB16C']) # Add sample data for i in range(100): a, b = rnd.rand(2) col = cmap.color(a, b) #this is where the magic happens circle = plt.Circle((a, b), 0.05, color=col) ax.add_artist(circle) # Add legends cmap.colorbar(cax) cax.set_ticks([(1, 0), (0, 0), (0, 1)], '') cax.set_ticklabels(['x', 'same', 'y']) # %% Sample use of ColorMap3, short cmap = p2c.ColorMap3(['#D87A11', '#F39935'], ['#6C2FB1'], ['blue']) cmap.color(0.2, 0.5, -0.3) #(0.5864, 0.2974, 0.4528, 1.0) # %% Sample use of ColorMap3, longer # Set-up canvas
def region_plot(file_name, regions=None, crystal_pos=True, peak_ct=True, beamdiam=100e-9, scanpx=2e-8, figsize=(10, 10), **kwargs): meta = get_meta_lists(file_name) cmap = plt.cm.jet fhs = [] if regions is None: regions = meta['shots']['region'].drop_duplicates().values if not hasattr(regions, '__iter__'): regions = (regions,) for reg in regions: shots = meta['shots'].loc[meta['shots']['region'] == reg, :] if not len(shots): print('Region {} does not exist. Skipping.'.format(reg)) continue shot = shots.iloc[0, :] fh = plt.figure(figsize=figsize, **kwargs) fhs.append(fh) ax = plt.axes() ax.set_title('Set: {}, Region: {}, Run: {}, # Crystals: {}'.format(shot['subset'], shot['region'], shot['run'], shots['crystal_id'].max())) stem = get_meta_array(file_name, 'stem', shot) ax.imshow(stem, cmap='gray') if 'acqdata' in meta.keys(): acqdata = meta['acquisition_data'].loc[shot['file']] pxs = float(acqdata['Scanning_Pixel_size_x']) else: pxs = scanpx * 1e9 if crystal_pos and peak_ct: norm = int(shots['peak_count'].quantile(0.99)) def ncmap(x): return cmap(x / norm) for idx, cr in shots.loc[:, ['crystal_x', 'crystal_y', 'peak_count']].drop_duplicates().iterrows(): ax.add_artist(plt.Circle((cr['crystal_x'], cr['crystal_y']), radius=beamdiam * 1e9 / 2 / pxs, facecolor=ncmap(cr['peak_count']), alpha=1)) # some gymnastics to get a colorbar Z = [[0, 0], [0, 0]] levels = range(0, norm, 1) CS3 = plt.contourf(Z, levels, cmap=plt.cm.jet) plt.colorbar(CS3, fraction=0.046, pad=0.04) del (CS3) elif crystal_pos: for idx, cr in shots.loc[:, ['crystal_x', 'crystal_y']].drop_duplicates().iterrows(): ax.add_artist( plt.Circle((cr['crystal_x'], cr['crystal_y']), radius=beamdiam * 1e9 / 2 / pxs, facecolor='r', alpha=1)) ax.add_artist(AnchoredSizeBar(ax.transData, 5000 / pxs, '5 um', 'lower right', pad=0.3, size_vertical=1)) ax.axis('off') return fhs
def plot(self): """Plots the charge.""" color = 'b' if self.q < 0 else 'r' if self.q > 0 else 'k' r = 0.1*(sqrt(fabs(self.q))/2 + 1) circle = pyplot.Circle(self.x, r, color=color, zorder=10) pyplot.gca().add_artist(circle)
import matplotlib.pyplot as plt import numpy as np label = ['Fri Dec 07', 'null'] tweet_count = [205735, 1941] colors = ['orange', 'seagreen'] fig1, ax1 = plt.subplots() ax1.pie(tweet_count, colors=colors, labels=label, explode=(0.0, 0.0), autopct='%1.1f%%', startangle=90) # draw circle centre_circle = plt.Circle((0, 0), fc='white') fig = plt.gcf() fig.gca().add_artist(centre_circle) # Equal aspect ratio ensures that pie is drawn as a circle ax1.axis('equal') plt.tight_layout() plt.title('Tweets activity based on Date') plt.show()
def plot_eigs(self, show_axes=True, show_unit_circle=True, figsize=(8, 8), title='', level=None, node=None): """ Plot the eigenvalues. :param bool show_axes: if True, the axes will be showed in the plot. Default is True. :param bool show_unit_circle: if True, the circle with unitary radius and center in the origin will be showed. Default is True. :param tuple(int,int) figsize: tuple in inches of the figure. :param str title: title of the plot. :param int level: plot only the eigenvalues of specific level. :param int node: plot only the eigenvalues of specific node. """ if self.eigs is None: raise ValueError('The eigenvalues have not been computed.' 'You have to perform the fit method.') if level: peigs = self.partial_eigs(level=level, node=node) else: peigs = self.eigs plt.figure(figsize=figsize) plt.title(title) plt.gcf() ax = plt.gca() if not level: cmap = plt.get_cmap('viridis') colors = [ cmap(i) for i in np.linspace(0, 1, len(self.dmd_tree.levels)) ] points = [] for level in self.dmd_tree.levels: eigs = self.partial_eigs(level) points.append( ax.plot(eigs.real, eigs.imag, '.', color=colors[level])[0]) else: points = [] points.append( ax.plot(peigs.real, peigs.imag, 'bo', label='Eigenvalues')[0]) # set limits for axis limit = np.max(np.ceil(np.absolute(peigs))) ax.set_xlim((-limit, limit)) ax.set_ylim((-limit, limit)) plt.ylabel('Imaginary part') plt.xlabel('Real part') if show_unit_circle: unit_circle = plt.Circle((0., 0.), 1., color='green', fill=False, linestyle='--') ax.add_artist(unit_circle) # Dashed grid gridlines = ax.get_xgridlines() + ax.get_ygridlines() for line in gridlines: line.set_linestyle('-.') ax.grid(True) ax.set_aspect('equal') # x and y axes if show_axes: ax.annotate('', xy=(np.max([limit * 0.8, 1.]), 0.), xytext=(np.min([-limit * 0.8, -1.]), 0.), arrowprops=dict(arrowstyle="->")) ax.annotate('', xy=(0., np.max([limit * 0.8, 1.])), xytext=(0., np.min([-limit * 0.8, -1.])), arrowprops=dict(arrowstyle="->")) # legend if level: labels = ['Eigenvalues - level {}'.format(level)] else: labels = [ 'Eigenvalues - level {}'.format(i) for i in range(self.max_level) ] if show_unit_circle: points += [unit_circle] labels += ['Unit circle'] ax.add_artist(plt.legend(points, labels, loc='best')) plt.show()
text = open('sample.txt', 'r', encoding='utf-8').read() stopwords = set(STOPWORDS) wordcloud = WordCloud(background_color='white', max_words=200, stopwords=stopwords) wordcloud.generate(text) fig18 = plt.imshow(wordcloud, interpolation='bilinear') plt.savefig('wordcloud.png') plt.axis('off') plt.show() # 11. Doughnut Chart top5_list = df.nlargest(5, 'total').index.tolist() df_top5 = pd.DataFrame(df.loc[top5_list, 'total'].T) circle = plt.Circle((0, 0), 0.7, color='white') colors = [ 'gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'lightgreen', 'pink' ] plt.pie(df_top5['total'], autopct='%1.1f%%', shadow=True, explode=[0.1, 0, 0, 0, 0], colors=colors, startangle=90) fig20 = plt.gcf() fig20.gca().add_artist(circle) plt.legend(df_top5.index, fontsize=12, loc='upper left') plt.title('Top 5 Immigrant Country Distribution', color='black', fontsize=18) plt.axis('equal') plt.savefig('doughnut.png')
def circle(self, colorstr='b', fillbool=False): return plt.Circle((self.x, self.y), self.r, color=colorstr, fill=fillbool)
def pro7plotstack(eq_file, plot_scale_fac=0.05, slow_delta=0.0005, slowR_lo=-0.1, slowR_hi=0.1, slowT_lo=-0.1, slowT_hi=0.1, start_buff=-50, end_buff=50, snaptime=8, snaps=10, ZslowR_lo=-0.1, ZslowR_hi=0.1, ZslowT_lo=-0.1, ZslowT_hi=0.1, Zstart_buff=50, Zend_buff=50, zoom=0, plot_dyn_range=1000, fig_index=401, skip_T=1, skip_R=0, ARRAY=0): import obspy import obspy.signal from obspy import UTCDateTime from obspy import Stream, Trace from obspy import read import numpy as np import os import matplotlib.pyplot as plt import math import time print('Running pro7a_plot_envstack') start_time_wc = time.time() if ARRAY == 0: file = open(eq_file, 'r') elif ARRAY == 1: goto = '/Users/vidale/Documents/PyCode/LASA/EvLocs' os.chdir(goto) file = open(eq_file, 'r') lines = file.readlines() split_line = lines[0].split() # ids.append(split_line[0]) ignore label for now t = UTCDateTime(split_line[1]) date_label = split_line[1][0:10] #%% Input parameters # #%% Get saved event info, also used to name files # date_label = '2018-04-02' # date for filename if ARRAY == 0: fname = 'HD' + date_label + '_2dstack_env.mseed' elif ARRAY == 1: goto = '/Users/vidale/Documents/PyCode/LASA/Pro_Files' fname = 'HD' + date_label + '_2dstack_env.mseed' os.chdir(goto) st = Stream() st = read(fname) print('Read in: ' + str(len(st)) + ' traces') nt = len(st[0].data) dt = st[0].stats.delta print('First trace has : ' + str(nt) + ' time pts, time sampling of ' + str(dt) + ' and thus duration of ' + str((nt - 1) * dt)) #%% Make grid of slownesses slowR_n = int(1 + (slowR_hi - slowR_lo) / slow_delta) # number of slownesses slowT_n = int(1 + (slowT_hi - slowT_lo) / slow_delta) # number of slownesses stack_nt = int(1 + ((end_buff - start_buff) / dt)) # number of time points print( str(slowT_n) + ' trans slownesses, hi and lo are ' + str(slowT_hi) + ' ' + str(slowT_lo)) # In English, stack_slows = range(slow_n) * slow_delta - slow_lo a1R = range(slowR_n) a1T = range(slowT_n) stack_Rslows = [(x * slow_delta + slowR_lo) for x in a1R] stack_Tslows = [(x * slow_delta + slowT_lo) for x in a1T] print( str(slowR_n) + ' radial slownesses, ' + str(slowT_n) + ' trans slownesses, ') #%% select subset for plotting if zoom == 1: Zst = Stream() for slowR_i in range(slowR_n): # loop over radial slownesses for slowT_i in range(slowT_n): # loop over transverse slownesses if ((stack_Rslows[slowR_i] >= ZslowR_lo) and (stack_Rslows[slowR_i] <= ZslowR_hi) and (stack_Tslows[slowT_i] >= ZslowT_lo) and (stack_Tslows[slowT_i] <= ZslowT_hi)): index = slowR_i * slowT_n + slowT_i s_t = t - Zstart_buff e_t = t + Zend_buff Zst += st[index].trim(starttime=s_t, endtime=e_t) #tr.trim(starttime=s_t,endtime = e_t) st = Zst nt = len(st[0].data) #%% Re-make grid of slownesses slowR_lo = ZslowR_lo slowR_hi = ZslowR_hi slowT_lo = ZslowT_lo slowT_hi = ZslowT_hi end_buff = Zend_buff start_buff = -Zstart_buff slowR_n = int( 1 + (slowR_hi - slowR_lo) / slow_delta) # number of slownesses slowT_n = int( 1 + (slowT_hi - slowT_lo) / slow_delta) # number of slownesses stack_nt = int(1 + ((end_buff - start_buff) / dt)) # number of time points print('After zoom ' + str(slowT_n) + ' trans slownesses, hi and lo are ' + str(slowT_hi) + ' ' + str(slowT_lo)) # In English, stack_slows = range(slow_n) * slow_delta - slow_lo a1R = range(slowR_n) a1T = range(slowT_n) stack_Rslows = [(x * slow_delta + slowR_lo) for x in a1R] stack_Tslows = [(x * slow_delta + slowT_lo) for x in a1T] print('After zoom ' + str(slowR_n) + ' radial slownesses, ' + str(slowT_n) + ' trans slownesses, ') #%% Find transverse slowness nearest zero if skip_R != 1: lowest_Tslow = 1000000 for slow_i in range(slowT_n): if abs(stack_Tslows[slow_i]) < lowest_Tslow: lowest_Tindex = slow_i lowest_Tslow = abs(stack_Tslows[slow_i]) print( str(slowT_n) + ' T slownesses, ' + str(lowest_Tindex) + ' min T slow, min is ' + str(lowest_Tslow)) # Select only stacks with that slowness for Radial plot centralR_st = Stream() for slowR_i in range(slowR_n): centralR_st += st[slowR_i * slowT_n + lowest_Tindex] #%% Slices near radial slownesses of zero, 0.005, 0.01, 0.015 if skip_T != 1: lowest_Rslow = 1000000 for slow_i in range(slowR_n): if abs(stack_Rslows[slow_i]) < lowest_Rslow: lowest_Rindex00 = slow_i lowest_Rslow = abs(stack_Rslows[slow_i]) print(str(slowR_n) + ' R slownesses, ') print( f'{lowest_Rindex00:4d} is R slow nearest 0, slowness is {lowest_Rslow:.3f}' ) # Select only stacks with that slowness for Radial plot centralT00_st = Stream() for slowT_i in range(slowT_n): centralT00_st += st[lowest_Rindex00 * slowT_n + slowT_i] #%% Slice near radial slowness of 0.005 lowest_Rslow = 1000000 for slow_i in range(slowR_n): if abs(stack_Rslows[slow_i] - 0.005) < lowest_Rslow: lowest_Rindex05 = slow_i lowest_Rslow = abs(stack_Rslows[slow_i] - 0.005) print( f'{lowest_Rindex05:4d} is R slow nearest 0.005, slowness is {lowest_Rslow + 0.005:.3f}' ) # Select only stacks with that slowness for Radial plot centralT05_st = Stream() for slowT_i in range(slowT_n): centralT05_st += st[lowest_Rindex05 * slowT_n + slowT_i] #%% Slice near radial slowness of 0.01 lowest_Rslow = 1000000 for slow_i in range(slowR_n): if abs(stack_Rslows[slow_i] - 0.01) < lowest_Rslow: lowest_Rindex10 = slow_i lowest_Rslow = abs(stack_Rslows[slow_i] - 0.01) print( f'{lowest_Rindex10:4d} is R slow nearest 0.010, slowness is {lowest_Rslow + 0.010:.3f}' ) # Select only stacks with that slowness for Radial plot centralT10_st = Stream() for slowT_i in range(slowT_n): centralT10_st += st[lowest_Rindex10 * slowT_n + slowT_i] #%% Slice near radial slowness of 0.015 lowest_Rslow = 1000000 for slow_i in range(slowR_n): if abs(stack_Rslows[slow_i] - 0.015) < lowest_Rslow: lowest_Rindex15 = slow_i lowest_Rslow = abs(stack_Rslows[slow_i] - 0.015) print( f'{lowest_Rindex15:4d} is R slow nearest 0.015, slowness is {lowest_Rslow + 0.015:.3f}' ) # Select only stacks with that slowness for Radial plot centralT15_st = Stream() for slowT_i in range(slowT_n): centralT15_st += st[lowest_Rindex15 * slowT_n + slowT_i] #%% total_slows = slowR_n * slowT_n global_max = 0 print('number of elements in total_slows is ' + str(total_slows)) print('slowR_n and slowT_n are ' + str(slowR_n) + ' ' + str(slowT_n)) print('st has ' + str(len(st)) + ' seismograms') for slow_i in range( total_slows): # find global max, and if requested, take envelope if len(st[slow_i].data) == 0: print('%d data has zero length ' % (slow_i)) local_max = max(abs(st[slow_i].data)) if local_max > global_max: global_max = local_max min_allowed = global_max / plot_dyn_range #%% compute timing time series ttt = (np.arange(len(st[0].data)) * st[0].stats.delta + start_buff ) # in units of seconds #%% Plotting # Regular radial-time stack if skip_R != 1: stack_array = np.zeros((slowR_n, stack_nt)) for it in range(stack_nt): # check points one at a time for slowR_i in range( slowR_n): # for this station, loop over slownesses num_val = centralR_st[slowR_i].data[it] if num_val < min_allowed: num_val = min_allowed stack_array[slowR_i, it] = math.log10(num_val) stack_array[0, 0] = math.log10(global_max) stack_array[0, 1] = math.log10(min_allowed) y, x = np.mgrid[slice(stack_Rslows[0], stack_Rslows[-1] + slow_delta, slow_delta), slice(ttt[0], ttt[-1] + dt, dt)] fig, ax = plt.subplots(1, figsize=(10, 3)) c = ax.pcolormesh(x, y, stack_array, cmap=plt.cm.gist_rainbow_r) ax.axis([x.min(), x.max(), y.min(), y.max()]) fig.colorbar(c, ax=ax) plt.xlabel('Time (s)') plt.ylabel('Slowness (s/km)') plt.title('Radial stack at 0 T slow, ' + fname[12:22]) plt.show() #%% Transverse-time stacks if skip_T != 1: stack_array = np.zeros((slowT_n, stack_nt)) for it in range(stack_nt): # check points one at a time for slowT_i in range( slowT_n): # for this station, loop over slownesses num_val = centralT00_st[slowT_i].data[it] if num_val < min_allowed: num_val = min_allowed stack_array[slowT_i, it] = math.log10(num_val) stack_array[0, 0] = math.log10(global_max) stack_array[0, 1] = math.log10(min_allowed) y, x = np.mgrid[slice(stack_Tslows[0], stack_Tslows[-1] + slow_delta, slow_delta), slice(ttt[0], ttt[-1] + dt, dt)] fig, ax = plt.subplots(1, figsize=(10, 3)) c = ax.pcolormesh(x, y, stack_array, cmap=plt.cm.gist_rainbow_r) ax.axis([x.min(), x.max(), y.min(), y.max()]) fig.colorbar(c, ax=ax) plt.xlabel('Time (s)') plt.ylabel('Slowness (s/km)') plt.title('Transverse stack at 0.000 R slow, ' + fname[12:22]) plt.show() fig_index += 1 stack_array = np.zeros((slowT_n, stack_nt)) for it in range(stack_nt): # check points one at a time for slowT_i in range( slowT_n): # for this station, loop over slownesses num_val = centralT05_st[slowT_i].data[it] if num_val < min_allowed: num_val = min_allowed stack_array[slowT_i, it] = math.log10(num_val) stack_array[0, 0] = math.log10(global_max) stack_array[0, 1] = math.log10(min_allowed) y, x = np.mgrid[slice(stack_Tslows[0], stack_Tslows[-1] + slow_delta, slow_delta), slice(ttt[0], ttt[-1] + dt, dt)] fig, ax = plt.subplots(1, figsize=(10, 3)) c = ax.pcolormesh(x, y, stack_array, cmap=plt.cm.gist_rainbow_r) ax.axis([x.min(), x.max(), y.min(), y.max()]) fig.colorbar(c, ax=ax) plt.xlabel('Time (s)') plt.ylabel('Slowness (s/km)') plt.title('Transverse stack at 0.005 R slow, ' + fname[12:22]) plt.show() fig_index += 1 stack_array = np.zeros((slowT_n, stack_nt)) for it in range(stack_nt): # check points one at a time for slowT_i in range( slowT_n): # for this station, loop over slownesses num_val = centralT10_st[slowT_i].data[it] if num_val < min_allowed: num_val = min_allowed stack_array[slowT_i, it] = math.log10(num_val) stack_array[0, 0] = math.log10(global_max) stack_array[0, 1] = math.log10(min_allowed) y, x = np.mgrid[slice(stack_Tslows[0], stack_Tslows[-1] + slow_delta, slow_delta), slice(ttt[0], ttt[-1] + dt, dt)] fig, ax = plt.subplots(1, figsize=(10, 3)) c = ax.pcolormesh(x, y, stack_array, cmap=plt.cm.gist_rainbow_r) ax.axis([x.min(), x.max(), y.min(), y.max()]) fig.colorbar(c, ax=ax) plt.xlabel('Time (s)') plt.ylabel('Slowness (s/km)') plt.title('Transverse stack at 0.010 R slow, ' + fname[12:22]) plt.show() fig_index += 1 stack_array = np.zeros((slowT_n, stack_nt)) for it in range(stack_nt): # check points one at a time for slowT_i in range( slowT_n): # for this station, loop over slownesses num_val = centralT15_st[slowT_i].data[it] if num_val < min_allowed: num_val = min_allowed stack_array[slowT_i, it] = math.log10(num_val) stack_array[0, 0] = math.log10(global_max) stack_array[0, 1] = math.log10(min_allowed) y, x = np.mgrid[slice(stack_Tslows[0], stack_Tslows[-1] + slow_delta, slow_delta), slice(ttt[0], ttt[-1] + dt, dt)] fig, ax = plt.subplots(1, figsize=(10, 3)) c = ax.pcolormesh(x, y, stack_array, cmap=plt.cm.gist_rainbow_r) ax.axis([x.min(), x.max(), y.min(), y.max()]) fig.colorbar(c, ax=ax) plt.xlabel('Time (s)') plt.ylabel('Slowness (s/km)') plt.title('Transverse stack at 0.015 R slow, ' + fname[12:22]) plt.show() #%% R-T stack if snaps > 0: stack_slice = np.zeros((slowR_n, slowT_n)) for snap_num in range(snaps): fig_index += 1 it = int((snaptime - start_buff) / dt) + snap_num for slowR_i in range(slowR_n): # loop over radial slownesses for slowT_i in range( slowT_n): # loop over transverse slownesses index = slowR_i * slowT_n + slowT_i num_val = st[index].data[it] if num_val < min_allowed: num_val = min_allowed stack_slice[slowR_i, slowT_i] = math.log10(num_val) stack_slice[0, 0] = math.log10(global_max) stack_slice[0, 1] = math.log10(min_allowed) y1, x1 = np.mgrid[slice(stack_Rslows[0], stack_Rslows[-1] + slow_delta, slow_delta), slice(stack_Tslows[0], stack_Tslows[-1] + slow_delta, slow_delta)] fig, ax = plt.subplots(1) c = ax.pcolormesh(x1, y1, stack_slice, cmap=plt.cm.gist_rainbow_r) ax.axis([x1.min(), x1.max(), y1.min(), y1.max()]) fig.colorbar(c, ax=ax) circle1 = plt.Circle((0, 0), 0.019, color='black', fill=False) ax.add_artist(circle1) plt.xlabel('T Slowness (s/km)') plt.ylabel('R Slowness (s/km)') plt.title('T-R stack at rel time ' + str(snaptime + snap_num * dt) + ' ' + fname[12:22]) plt.show() # Save processed files # fname = 'HD' + date_label + '_slice.mseed' # stack.write(fname,format = 'MSEED') elapsed_time_wc = time.time() - start_time_wc print('This job took ' + str(elapsed_time_wc) + ' seconds') os.system('say "Done"')
dims = dens.shape nz, ny, nx = dims # # data_part = load_snapshot_data_particles( nSnap, inputDir ) # # dens_part = data_part['density'] if time == 0: r_interp = 0.2 else: r_interp = np.interp(time, t_all, radius_all) # print time, r_interp fig, ax1 = plt.subplots(nrows=1, ncols=1, figsize=(12, 10)) cut = nz / 2 circle1 = plt.Circle((0.5, 0.5), r_interp, color='white', fill=False, linewidth=1.2) data = dens[cut, :, :] img = ax1.imshow(data, extent=[0, 1, 0, 1], cmap='jet') divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.05) cb = fig.colorbar( img, cax=cax, ) cb.set_label('Density', fontsize=16) ax1.set_xlabel('X') ax1.set_ylabel('Y')
axs[0, 0].hist(x) axs[1, 1].hist(y, orientation="horizontal") plt.show() ############################################################################ # Square joint/marginal plot # ~~~~~~~~~~~~~~~~~~~~~~~~~~ # # When setting the box aspect, one may still set the data aspect as well. # Here we create an axes with a box twice as long as tall and use an "equal" # data aspect for its contents, i.e. the circle actually stays circular. fig6, ax = plt.subplots() ax.add_patch(plt.Circle((5, 3), 1)) ax.set_aspect("equal", adjustable="datalim") ax.set_box_aspect(0.5) ax.autoscale() plt.show() ############################################################################ # Box aspect for many subplots # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # It is possible to pass the box aspect to an axes at initialization. The # following creates a 2 by 3 subplot grid with all square axes. fig7, axs = plt.subplots(2, 3, subplot_kw=dict(box_aspect=1), sharex=True, sharey=True, constrained_layout=True)
def __init__(self, Path, display_img, Pixel): # Initialisation of the arrays sliceList = [] middleslicex = [] middleslicey = [] x = [] i = Padding_bottom # loop for each .dcm file length = len(listdir(Path)) - 1 files = [f for f in listdir(Path)] files = sorted(files) pb_hD.maximum = length for i, f in enumerate(files): if StopRun == True: break if (i <= length - Padding_top and i >= Padding_bottom): if int(i * 100 / length) - int((i - 1) * 100 / length) == 1: pb_hD.step(1) pb_hD.update() ds = dicom.read_file(join(Path, f)) x = np.array(ds.pixel_array) if (i == Padding_bottom): a = x.shape[0] / 2 Offsetr = 2 * a * Offsetx / Diameter Offsetc = 2 * a * Offsety / Diameter # Filter the values x_masked = GetMaskedValues(x, Offsetr, Offsetc) sliceList.append(x_masked) middleslicex.insert(0, x[:, a + Offsetc]) middleslicey.insert(0, x[a + Offsetr, :]) #gather slices into a single np-matrix self.CTPixel = np.zeros([len(sliceList), len(sliceList[0])]) self.CTSlice = np.zeros([len(middleslicex), len(middleslicex[0])]) self.CTSlicey = np.zeros([len(middleslicey), len(middleslicey[0])]) for j in range(0, len(sliceList) - 1): self.CTPixel[j] = sliceList[j] self.CTSlice[j] = middleslicex[j] self.CTSlicey[j] = middleslicey[j] pb_hD.stop() # Show the image if (display_img): fig1 = plt.figure() ax1 = fig1.add_subplot(132, aspect='equal') ax1.set_title("XZ Slice") ax1.set_xlabel('X') ax1.set_ylabel('Z') ax1.matshow(self.CTSlice, cmap=plt.cm.gray, aspect='equal') ax1.add_patch( patches.Rectangle((a - Offsetr - a * Crop_pct, 0), 2 * a * Crop_pct, length, fill=False, edgecolor="red")) ax3 = fig1.add_subplot(133, aspect='equal') ax3.set_title("YZ Slice") ax3.set_xlabel('Y') ax3.set_ylabel('Z') ax3.matshow(self.CTSlicey, cmap=plt.cm.gray, aspect='equal') ax3.add_patch( patches.Rectangle((a - Offsetc - a * Crop_pct, 0), 2 * a * Crop_pct, length, fill=False, edgecolor="red")) ax2 = fig1.add_subplot(131, aspect='equal') ax2.set_title("XY Slice") ax2.set_xlabel('X') ax2.set_ylabel('Y') ax2.imshow(ds.pixel_array, cmap=pylab.cm.bone) circle = plt.Circle((a + Offsetr, a + Offsetc), a * Crop_pct, color='r', linewidth=1, fill=False) plt.gcf().gca().add_artist(circle) ax2.plot((a - 10 + Offsetr, a + 10 + Offsetr), (a + Offsetc, a + Offsetc), 'k') ax2.plot((a + Offsetr, a + Offsetr), (a - 10 + Offsetc, a + 10 + Offsetc), 'k') plt.tight_layout() canvas = FigureCanvasTkAgg(fig1, master=stepFour) canvas.show() canvas.get_tk_widget().grid(row=0, column=0, columnspan=3, pady=2, sticky='W') form.update()
def plotDecodedGenesOnWholeImage(path_to_original_image: str, path_to_spotsCSV: str, tile_grid_shape: Tuple[int, int], tile_size_x: int, tile_size_y: int): image = io.imread(path_to_original_image) df = pd.read_csv(path_to_spotsCSV) genes_list = set(df['Gene']) # Making a colormap that picks a different color for each gene (and empty string) cmap = plt.get_cmap('gist_rainbow') colors = cmap(np.linspace(0, 1, len(genes_list))) color_dict = {gene: color for gene, color in zip(genes_list, colors)} ## Calculate image properties: total_n_tiles, tile_grid_array, original_x, original_y = calculateTileGridStatistics( tile_grid_shape, tile_size_x, tile_size_y) fig, ax = plt.subplots(1, 1) ax.imshow(image, cmap='gray') ax.set_title("Decoded genes") for row in df.itertuples(): # extract X and Y coordinates of the respective tile the spot belongs to row_location, col_location = np.where( tile_grid_array == row.Tile ) # this returns rows and columns, NOT X and Y, which is the opposite # unpacking the array structure of the return tuple of np.where y_tile_location, x_tile_location = row_location[0], col_location[0] # Calculate how many pixels to add in order to plot the spot in the correct tile in the original image x_adder = x_tile_location * tile_size_x y_adder = y_tile_location * tile_size_y # Calculate the position in the original image x_coordinate = row.X + x_adder y_coordinate = row.Y + y_adder gene = row.Gene if str(gene) != "nan": ## Now we plot the dot circ = plt.Circle((x_coordinate, y_coordinate), radius=2, color=color_dict[gene], label=gene) ax.add_patch(circ) # legendWithoutDuplicateLabels(ax) fig.tight_layout() plt.axis('off') plt.savefig("decoded_genes_plotted.pdf") # plt.show() # Now the same with nonrecognized spots included fig, ax = plt.subplots(1, 1) ax.imshow(image, cmap='gray') ax.set_title("Decoded genes") for row in df.itertuples(): # extract X and Y coordinates of the respective tile the spot belongs to row_location, col_location = np.where( tile_grid_array == row.Tile ) # this returns rows and columns, NOT X and Y, which is the opposite # unpacking the array structure of the return tuple of np.where y_tile_location, x_tile_location = row_location[0], col_location[0] # Calculate how many pixels to add in order to plot the spot in the correct tile in the original image x_adder = x_tile_location * tile_size_x y_adder = y_tile_location * tile_size_y # Calculate the position in the original image x_coordinate = row.X + x_adder y_coordinate = row.Y + y_adder gene = row.Gene ## Now we plot the dot circ = plt.Circle((x_coordinate, y_coordinate), radius=2, color=color_dict[gene], label=str(gene)) ax.add_patch(circ) # legendWithoutDuplicateLabels(ax) fig.tight_layout() plt.savefig("all_decoded_spots_plotted.pdf")
def PlotTraj(dx, v0x, vf, obs_t, obs_offset,wpts,ax1): cmd = "./bin/solve {} {} {} {} {} {} {} {}".format( 'token.txt',round(dx[0],3),round(dx[1],3),round(v0x, 3), round(vf[0],3),round(vf[1],3),round(obs_t,3),round(obs_offset,3)) try: status = subprocess.call(cmd, shell=True, timeout=1) except: print("timeout on command:") print(cmd) return float('inf'), float('inf') if status > 0: return float('inf'), float('inf') with open('token.txt') as csvfile: lines = csv.reader(csvfile, delimiter=',') ii=0 traj_mat=[0,0] for row in lines: ii=ii+1 if ii==2: obs_xy=[float(i) for i in row] if ii>=6: traj_pt=[float(i) for i in row] traj_mat=np.vstack((traj_mat,[traj_pt[1],traj_pt[2]])) ax1.plot(traj_mat[:,0],traj_mat[:,1]) ax1.plot(0,0,'x') ax1.plot(dx[0],dx[1],'x') wpts=np.matrix(wpts) circle1=plt.Circle((obs_xy[0],obs_xy[1]),0.18,color='r',label='Obstacle region') ax1.add_patch(circle1) #print(wpts) for iindex in range(np.size(wpts,axis=1)): #for wpt in wpts: wpt=(wpts[iindex,:]) ax1.plot(wpt[:,0],wpt[:,1],'o') cmd = "./bin/eval {} {} {} {} {} {} {} {} {} {} {} {}".format( 'token.txt',round(dx[0],3),round(dx[1],3),round(v0x, 3), round(vf[0],3),round(vf[1],3),float(wpt[:,0]),float(wpt[:,1]), float(wpt[:,2]),float(wpt[:,3]),round(obs_xy[0],3),round(obs_xy[1],3)) try: status = subprocess.call(cmd, shell=True, timeout=1) except: print("timeout on command:") print(cmd) return float('inf'), float('inf') if status > 0: return float('inf'), float('inf') with open('token.txt') as csvfile: lines = csv.reader(csvfile, delimiter=',') ii=0 traj_mat=[0,0] for row in lines: ii=ii+1 if ii>=4: traj_pt=[float(i) for i in row] traj_mat=np.vstack((traj_mat,[traj_pt[1],traj_pt[2]])) print() ax1.plot(traj_mat[:,0],traj_mat[:,1]) return ax1
def draw_circle_frame(self, x0, y0, r): return plt.Circle((x0, y0), r)
from mpl_toolkits import mplot3d import matplotlib.pyplot as plt from rosenbrock import * def f(a, b): return a * b if __name__ == "__main__": x = np.linspace(-6, 6, 30) y = np.linspace(-6, 6, 30) X, Y = np.meshgrid(x, y) Z = f(X, Y) fig = plt.figure() ax = plt.axes(projection='3d') ax.contour3D(X, Y, Z, 200, cmap='magma') c1 = plt.Circle((0, 0), 0.0040, color='green', fill=False) ax.add_artist(c1) ax.view_init(40, 30) fig.show() fig.show()