def chickling_pd_zoom(shotno, date=time.strftime("%Y%m%d")): fname, data = file_finder(shotno,date) data_1550 = data[0]['phasediff_co2'][100:] plot_time = np.linspace(0,1,data_1550.size) fig, ax = plt.subplots() ax.plot(plot_time, data_1550) ax.set_ybound(max(data_1550)+0.6, min(data_1550)-0.01) plt.title("Phase Difference for shot " + str(shotno) + " Date " + str(date)) plt.xlabel("Time, s") plt.ylabel("Phase Difference, Radians") x_zoom_bot = int(data_1550.size*(10/100)) x_zoom_top = int(data_1550.size*(15/100)) x1, x2, y1, y2 = 0.1, 0.15, max(data_1550[x_zoom_bot:x_zoom_top])+0.01, min(data_1550[x_zoom_bot:x_zoom_top])-0.01 axins = inset_axes(ax, 4.3,1, loc=9) axins.plot(plot_time[x_zoom_bot:x_zoom_top], data_1550[x_zoom_bot:x_zoom_top]) axins.set_xlim(x1, x2) if y1 < y2: axins.set_ylim(y1, y2) else: axins.set_ylim(y2, y1) mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5",lw=2) plt.show()
def plotLineMatplotlib(self, x_list, y_list, value, unit): figureTitle = "{} for {}".format(value, self.dataDate.strftime(DATE_FORMAT)) logging.debug("Plotting {}".format(figureTitle)) output_file = "{}Plot.png".format(value.title().replace(' ', '')) df = pd.DataFrame({'time': x_list, value: y_list}) # plot figure, axes = plt.subplots(figsize=(16, 6)) axes.plot('time', value, data=df, marker='o', color='mediumvioletred') plt.title(figureTitle) plt.xlabel("Time") plt.ylabel('{} ({})'.format(value, unit)) plt.legend() plt.grid(True) plt.xticks([i.strftime("%H:%M") for i in x_list]) logging.debug(plt.xticks()) if unit == "*C": plt.ylim(0, 70) else: plt.ylim(0, 50) plt.savefig(output_file) plt.show()
def draw(self, ax, x_col, y_col, label, line_param_kwargs={}): print "X=",x_col,"Y=",y_col x_data = self.get_data(x_col); y_data = self.get_data(y_col); if False: filtered_indices = self.filter_outliers(y_data) else: #don't filter anything filtered_indices = range(0,len(y_data)) filtered_y_data = y_data[filtered_indices] mean,std = np.mean(filtered_y_data ), np.std(filtered_y_data ) ax.plot(x_data[filtered_indices], y_data[filtered_indices],label="%s"%(label),**(line_param_kwargs) );
def plot(self, **data): """ 1. scaning the parameter correct a) the parameter number equal to 2n. b) the parameter number less then 12 2.set the figure title 3. change the figure attribute 4.plot data 5.save plot figure the """ #if len(data)>14 or len(data)%2==1 or len(data)<4: # print 'parameter number wrong' # quit() #input data Xdata = data['Xdata'] Ydata = data['Ydata'] lengenddata = data['legenddata'] legendposition = data['legendposition'] ax = subplot(111) title(self.title, fontsize=20) xlabel(self.xtitle, fontsize=20) ylabel(self.ytitle, fontsize=20) if data['xscale'] == 'liner': 0 == 0 else: ax.set_xscale('log', basex=int(data['xscale'])) if data['yscale'] == 'liner': 0 == 0 else: ax.set_yscale('log', basey=int(data['yscale'])) #plt.yscale('log') # ax.xaxis.set_major_locator(MultipleLocator(0.0005))#set major scale # ax.xaxis.set_minor_locator(MultipleLocator(0.0001))#set mirror scale # ax.yaxis.set_major_locator(MultipleLocator(0.5))#set major scale # ax.yaxis.set_minor_locator(MultipleLocator(0.1))#set mirror scale tts = [] gca().yaxis.set_major_formatter(ScalarFormatter(useMathText=True)) for index in range(0, len(Xdata)): print index tt = ax.plot(Xdata[index], Ydata[index], self.marker[index], color=self.color[index]) # tts = tts + tt plt.legend(tts, lengenddata, numpoints=1, bbox_to_anchor=(legendposition[0], legendposition[1])) plt.show() plt.savefig(self.filename, dpi=300) pass
def draw(self, ax, x_col, y_col, label, line_param_kwargs={}): print "X=", x_col, "Y=", y_col x_data = self.get_data(x_col) y_data = self.get_data(y_col) if False: filtered_indices = self.filter_outliers(y_data) else: #don't filter anything filtered_indices = range(0, len(y_data)) filtered_y_data = y_data[filtered_indices] mean, std = np.mean(filtered_y_data), np.std(filtered_y_data) ax.plot(x_data[filtered_indices], y_data[filtered_indices], label="%s" % (label), **(line_param_kwargs))
def show_xz(self, axes): downsample = self.w_downsample.value() y = self.fixed_img.shape[1] // 2 min_x = min(self.fixed_img.shape[0], self.moving_img.shape[0]) min_z = min(self.fixed_img.shape[2], self.moving_img.shape[2]) fixed_slice = self.fixed_img[:min_x:downsample, y, :min_z:downsample].transpose() moving_slice = self.moving_img[:min_x:downsample, y, :min_z:downsample].transpose() combined = np.stack([fixed_slice, moving_slice, np.zeros_like(fixed_slice)], 2).astype(np.float32) clip = np.quantile(combined.flatten(), .90) combined = np.clip(combined, 0, clip) axes.imshow(combined) z_fixed = self.fixed_img_z.value() // downsample z_moving = self.moving_img_z.value() // downsample axes.plot([0, min_x // downsample], [z_fixed, z_fixed]) axes.plot([0, min_x // downsample], [z_moving, z_moving]) self.redo_axes_ticks(axes, min_x, min_z)
def plot(self,**data): """ 1. scaning the parameter correct a) the parameter number equal to 2n. b) the parameter number less then 12 2.set the figure title 3. change the figure attribute 4.plot data 5.save plot figure the """ #if len(data)>14 or len(data)%2==1 or len(data)<4: # print 'parameter number wrong' # quit() #input data Xdata = data['Xdata'] Ydata = data['Ydata'] lengenddata = data['legenddata'] legendposition = data['legendposition'] ax = subplot(111) title(self.title, fontsize=20) xlabel(self.xtitle, fontsize=20) ylabel(self.ytitle, fontsize=20) if data['xscale'] == 'liner': 0==0 else: ax.set_xscale('log',basex=int(data['xscale'])) if data['yscale'] == 'liner': 0==0 else: ax.set_yscale('log',basey=int(data['yscale'])) #plt.yscale('log') # ax.xaxis.set_major_locator(MultipleLocator(0.0005))#set major scale # ax.xaxis.set_minor_locator(MultipleLocator(0.0001))#set mirror scale # ax.yaxis.set_major_locator(MultipleLocator(0.5))#set major scale # ax.yaxis.set_minor_locator(MultipleLocator(0.1))#set mirror scale tts = [] gca().yaxis.set_major_formatter(ScalarFormatter(useMathText=True)) for index in range(0,len(Xdata)): print index tt = ax.plot(Xdata[index],Ydata[index],self.marker[index],color=self.color[index])# tts = tts+tt plt.legend(tts,lengenddata,numpoints=1,bbox_to_anchor=(legendposition[0], legendposition[1])) plt.show() plt.savefig(self.filename,dpi=300) pass
def show_yz(self, axes): downsample = self.w_downsample.value() x = self.fixed_img.shape[0] // 2 min_y = min(self.fixed_img.shape[1], self.moving_img.shape[1]) min_z = min(self.fixed_img.shape[2], self.moving_img.shape[2]) fixed_slice = self.fixed_img[x, :min_y:downsample, :min_z:downsample] moving_slice = self.moving_img[x, :min_y:downsample, :min_z:downsample] combined = np.stack([fixed_slice, moving_slice, np.zeros_like(fixed_slice)], 2).astype(np.float32) clip = np.quantile(combined.flatten(), .90) combined = np.clip(combined, 0, clip) axes.imshow(combined) z_fixed = self.fixed_img_z.value() // downsample z_moving = self.moving_img_z.value() // downsample axes.plot([z_fixed, z_fixed], [0, min_y // downsample]) axes.plot([z_moving, z_moving], [0, min_y // downsample]) self.redo_axes_ticks(axes, min_z, min_y)
def add_identity(axes, *line_args, **line_kwargs): # type: (matplotlib.axes.Axes, List[str], Dict[str, Any]) -> matplotlib.axes.Axes identity, = axes.plot([], [], *line_args, **line_kwargs) def callback(l_axes): low_x, high_x = l_axes.get_xlim() low_y, high_y = l_axes.get_ylim() low = max(low_x, low_y) high = min(high_x, high_y) identity.set_data([low, high], [low, high]) callback(axes) axes.callbacks.connect('xlim_changed', callback) axes.callbacks.connect('ylim_changed', callback) return axes
def plot_graph(train_history, label_col, mode): # Obtain scores from history loss = train_history.history['loss'] #List val_loss = train_history.history['val_loss'] #Check if binary or multiclass problem to obtain correct metrics if mode == 0: acc = train_history.history['binary_accuracy'] val_acc = train_history.history['val_binary_accuracy'] else: acc = train_history.history['categorical_accuracy'] val_acc = train_history.history['val_categorical_accuracy'] # Plot loss scores sns.set_style("whitegrid") fig, ax = plt.subplots(1, 1) ax.plot(loss, label = "Loss") ax.plot(val_loss, label = "Validation Loss") ax.set_title('Model Loss') ax.legend(loc = "upper right") ax.set_xlim([0, 100]) ax.set_ylabel("Loss") ax.set_xlabel("Epochs") ax.minorticks_on() ax.grid(b=True, which='major') ax.grid(b=True, which='minor') plt.savefig(results_dir + '/' + label_col + '_loss.png') plt.show() # Plot accuracy scores fig, ax = plt.subplots(1, 1) ax.plot(acc, label = "Accuracy") ax.plot(val_acc, label = "Validation Accuracy") ax.set_title('Model Accuracy') ax.legend(loc = "lower right") ax.set_xlim([0, 100]) ax.grid(b=True, which='major') ax.grid(b=True, which='minor') ax.set_ylabel("Accuracy") ax.set_xlabel("Epochs") ax.minorticks_on() plt.savefig(results_dir + '/' + label_col + '_acc.png') plt.show() return 0
def draw(self, output_name, x, y_list): plt.autoscale(True, 'both', True) fig = plt.figure(figsize=(100,10), dpi=300) lines = [] ax = fig.add_subplot(111) for y in y_list: ys = y.split(',') l = None if len(ys) > 1: l = ys[1] y = ys[0].replace('.','') line, = ax.plot(self.data[x], self.data[y], '-', label=l) lines.append(line) ax.set_xlabel(x) # handles, labels = ax.get_legend_handles_labels() ax.legend() plt.savefig(output_name, bbox_inches='tight') plt.clf()
def draw(self, output_name, x, y_list): plt.autoscale(True, 'both', True) fig = plt.figure(figsize=(100, 10), dpi=300) lines = [] ax = fig.add_subplot(111) for y in y_list: ys = y.split(',') l = None if len(ys) > 1: l = ys[1] y = ys[0].replace('.', '') line, = ax.plot(self.data[x], self.data[y], '-', label=l) lines.append(line) ax.set_xlabel(x) # handles, labels = ax.get_legend_handles_labels() ax.legend() plt.savefig(output_name, bbox_inches='tight') plt.clf()
def init_draw(self): self.scatter, = ax.plot(self.x, self.y, self.color)
def run(data): # update the data t,y = data if t>-1: xdata.append(t) ydata.append(y) #if t>xsize: # Scroll to the left. # ax.set_xlim(t-xsize, t) line.set_data(xdata, ydata) return line, def on_close_figure(event): sys.exit(0) data_gen.t = -1 fig = plt.figure() fig.canvas.mpl_connect('close_event', on_close_figure) ax = fig.add_subplot(111) line, = ax.plot([], linestyle='-.', lw=7, color = 'red') ax.set_ylim(0, 250) ax.set_xlim(0, 400) ax.grid() xdata, ydata = [], [] # Important: Although blit=True makes graphing faster, we need blit=False to prevent # spurious lines to appear when resizing the stripchart. ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=100, repeat=False) plt.show()
npArray = np.array(tamañosC2[x]) #tamañosC0[x] = tamañosC0[x].mean() resC2.append(tamañosC2[x].mean()) yTicks.append(tamañosC2[x].mean()) for index, x in enumerate(tamañosC3): npArray = np.array(tamañosC3[x]) #tamañosC0[x] = tamañosC0[x].mean() resC3.append(tamañosC3[x].mean()) yTicks.append(tamañosC3[x].mean()) with PdfPages('ImagenFantasma_C_vs_ASM.pdf') as pdf: fig, ax= plt.subplots() ax.plot(tamaños, resASM, label="ASM", marker=".") ax.plot(tamaños, resC0, label="C0", marker=".") ax.plot(tamaños, resC2, label="C2", marker=".") ax.plot(tamaños, resC3, label="C3", marker=".") ax.legend(['ASM','O0','O2','O3'], loc='upper left') plt.xlabel("Cantidad de pixeles") plt.ylabel("Ciclos de clock") plt.title("Imagen Fantasma") #ax.set_xTicks = ['512','2048','8192','32768','120000','131072','480000','1920000'] #ax.set_yTicks = [str(yTicks[i]) for i in range(0, len(yTicks))] ax.ticklabel_format(style='plain') ax.axis([0, 2000000, 0, 180000000]) plt.grid( linestyle='-', linewidth=1) for tick in ax.get_xticklabels(): tick.set_rotation(55) #plt.show()
def init_lines(): ''' Initial lines arguments: args parsed dictionary plotting arguments dictionaries a list of 1D series dictionary data to be plotted data_names names associated with the dictionaries to be plotted ''' if (args.hide_plot): PyPloter.switch_backend('agg') if len(series_pairs) is not len(data_names): print( "Error: len of dictionaries do not match length of associated data names" ) sys.exit(0) xname = args.x_value_name yname = args.y_value_name for series_pair, filename in zip(series_pairs, data_names): series_data = series_pair.grid index_key = next(iter(series_pair.index)) # find min and max of the data and write it to a file if necessary # clean file names if (args.data_file_name is not None): outputfile = open( args.data_file_name + '_' + filename.split('/')[-1] + '.' + re.sub(r'[^\w]', '', yname) + '.dat', 'w') xmin = (np.array(series_data[0][xname]) * args.scale_x).min() xmax = (np.array(series_data[0][xname]) * args.scale_x).max() ymin = (np.array(series_data[0][yname]) * args.scale_y).min() ymax = (np.array(series_data[0][yname]) * args.scale_y).max() for data, index_value in zip(series_data, series_pair.index[index_key]): x = np.array(data[xname]) * args.scale_x y = np.array(data[yname]) * args.scale_y xmin = min(x.min(), xmin) xmax = max(x.max(), xmax) ymin = min(y.min(), ymin) ymax = max(y.max(), ymax) if (args.data_file_name is not None): if (args.x_label is not None): header_xlabel = args.x_label else: header_xlabel = xname if (args.y_label is not None): header_ylabel = args.y_label else: header_ylabel = yname print('# ', index_key, header_xlabel, header_ylabel, file=outputfile) for x_value, y_value in zip(x, y): outstring = "%.9e" % (index_value) + " %.9e" % ( x_value * args.scale_x) + " %.9e" % ( y_value * args.scale_y) + "\n" outputfile.write(outstring) if (args.data_file_name is not None): print("data saved as -- " + args.data_file_name + '_' + filename.split('/')[-1] + '.' + re.sub(r'[^\w]', '', yname) + '.dat') outputfile.close() if (args.find_max_y): print(yname, "max y value ", ymax) if (args.find_min_y): print(yname, "min y value ", ymin) # initialize the figure and axes axes = PyPloter.axes(xlim=(xmin, xmax), ylim=(ymin, ymax)) lines = [] # initialize lines data for filename in data_names: data_name = '' line, = axes.plot([], []) if (args.line_names is not None): if (len(args.line_names) != len(args.data_names)): print( "number of line names doesn't match the number of plotted lines" ) print( "line names have to be specified either for ALL or NONE of the plotted lines" ) print("number of line names = ", len(args.tracer_names)) print("number of y_value_names = ", len(args.tracer_numbers)) sys.exit() for temp_name, line_name in zip(args.data_names, args.line_names): if (temp_name == filename): data_name = filename.split( '/')[-1] + " - " + line_name else: data_name = filename.split('/')[-1] + " " + str(yname) data_line_type = '' if (args.line_types is not None): if (len(args.line_types) != len(args.y_value_names)): print( "number of line types doesn't match the number of plotted lines" ) print( "line types have to be specified either for ALL or NONE of the lines" ) print("number of line types = ", len(args.line_types)) print("number of y_value_names = ", len(args.tracer_numbers)) sys.exit() for temp_y_name, line_type in zip(args.y_value_names, args.line_types): if (temp_y_name == yname): data_line_type = line_type.strip(' ') data_line_color = '' if (args.line_colors is not None): if (len(args.line_colors) != len(args.filenames)): print( "number of line colors doesn't match the number of inputs plotted" ) print( "line colors have to be specified either for ALL or NONE of the lines" ) print("number of line colors = ", len(args.line_colors)) print("number of files plotted = ", len(data_names)) sys.exit() for temp_filename, line_color in zip( data_names, args.line_colors): if (temp_filename == filename): data_line_color = line_color if (data_line_color != '' and data_line_type != ''): line, = axes.plot([], [], label=data_name, linestyle=data_line_type, color=data_line_color) elif (data_line_color != ''): line, = axes.plot([], [], label=data_name, color=data_line_color) elif (data_line_type != ''): line, = axes.plot([], [], label=data_name, linestyle=data_line_type) else: line, = axes.plot([], [], label=data_name) lines.append(line) if (args.x_label is not None): PyPloter.xlabel(args.x_label) else: PyPloter.xlabel(xname) if (args.x_limits is not None): PyPloter.xlim(args.x_limits) if (args.y_label is not None): PyPloter.ylabel(args.y_label) else: PyPloter.ylabel(yname) if (args.y_limits is not None): PyPloter.ylim(y_limits) if (args.plot_grid): PyPloter.grid() PyPloter.legend(loc='best') if (args.log_x): PyPloter.xscale("log") if (args.log_y): PyPloter.yscale("log") return lines
import matplotlib.pyplot as plt import matplotlib.axes as ax import pylab # change to proper directory os.chdir('C:\Users\Matt\Desktop\Python Projects\Exploratory Data Analysis') # load file, select proper date range, convert row to numeric dtypes hpc = pd.read_csv('household_power_consumption.txt', sep=';', index_col=['Date'], usecols=['Sub_metering_1', 'Sub_metering_2', 'Sub_metering_3', 'Date']) # hpc = hpc.drop(['Date', 'Time'], axis=1).set_index('DT') hpc = hpc['1/2/2007':'3/2/2007'].convert_objects(convert_numeric=True) hpc = hpc[0:2881] # create plotting variables x = pd.date_range('2/1/2007', '2/3/2007 00:00', freq='T') y1 = hpc.Sub_metering_1 y2 = hpc.Sub_metering_2 y3 = hpc.Sub_metering_3 fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(x, y1, color='k', label='Sub_metering_1') ax.plot(x, y2, color='r', label='Sub_metering_2') ax.plot(x, y3, color='b', label='Sub_metering_3') ax.legend(loc='best') ax.set_xticklabels(['Thur', '', '', '', 'Fri', '', '', '','Sat']) ax.set_yticklabels(['0', '', '10', '', '20', '', '30']) #plt.xlabel('Global Active Power (kilowatts)') ax.set_ylabel('Energy sub metering') #plt.title('Global Active Power') pylab.show()
# change to proper directory os.chdir('C:\Users\Matt\Desktop\Python Projects\Exploratory Data Analysis') # load file, select proper date range, convert row to numeric dtypes hpc = pd.read_csv( 'household_power_consumption.txt', sep=';', index_col=['Date'], usecols=['Sub_metering_1', 'Sub_metering_2', 'Sub_metering_3', 'Date']) # hpc = hpc.drop(['Date', 'Time'], axis=1).set_index('DT') hpc = hpc['1/2/2007':'3/2/2007'].convert_objects(convert_numeric=True) hpc = hpc[0:2881] # create plotting variables x = pd.date_range('2/1/2007', '2/3/2007 00:00', freq='T') y1 = hpc.Sub_metering_1 y2 = hpc.Sub_metering_2 y3 = hpc.Sub_metering_3 fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(x, y1, color='k', label='Sub_metering_1') ax.plot(x, y2, color='r', label='Sub_metering_2') ax.plot(x, y3, color='b', label='Sub_metering_3') ax.legend(loc='best') ax.set_xticklabels(['Thur', '', '', '', 'Fri', '', '', '', 'Sat']) ax.set_yticklabels(['0', '', '10', '', '20', '', '30']) #plt.xlabel('Global Active Power (kilowatts)') ax.set_ylabel('Energy sub metering') #plt.title('Global Active Power') pylab.show()
data = np.zeros((len(tVec),5)) data[:,0] = tVec data[:,1:] = state[:,9:13] np.savetxt(outDir+outBase, data, delimiter=",") #### Plotting the results # Turn on the minor TICKS, which are required for the minor GRID. mpl.rcParams['legend.fontsize'] = 10 ## Position plotting: fig = plt.figure(1) ax = fig.gca(aspect='equal',projection='3d') ax.plot(state[:,0]/1000, state[:,1]/1000, state[:,2]/1000, label='Orbital Position', color='k') # Sphere to represent Earth # Make data u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) xSphere = rEarth/1000 * np.outer(np.cos(u), np.sin(v)) ySphere = rEarth/1000 * np.outer(np.sin(u), np.sin(v)) zSphere = rEarth/1000 * np.outer(np.ones(np.size(u)), np.cos(v)) # Plot the surface ax.plot_surface(xSphere, ySphere, zSphere, cmap='GnBu') # Legend and labels. ax.legend() ax.set_xlabel('X Pos (km)') ax.set_ylabel('Y Pos (km)')
if t > xsize: # Scroll to the left. ax.set_xlim(t - xsize, t) line.set_data(xdata, ydata) return line, def on_close_figure(event): sys.exit(0) data_gen.t = -1 fig = plt.figure() fig.canvas.mpl_connect('close_event', on_close_figure) ax = fig.add_subplot(111) line, = ax.plot([], [], lw=2) ax.set_ylim(0, 250) ax.set_xlim(0, xsize) ax.grid() xdata, ydata = [], [] # Important: Although blit=True makes graphing faster, we need blit=False to prevent # spurious lines to appear when resizing the stripchart. ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=100, repeat=False) plt.show()
x = np.linspace(chi2.ppf(0.01, df), chi2.ppf(0.99, df), 100) xu = np.linspace(chi2.ppf(0.01, dof), chi2.ppf(0.99, dof), 100) xu1 = np.linspace(chi2.ppf(0.01, dof1), chi2.ppf(0.99, dof1), 100) xu2 = np.linspace(chi2.ppf(0.01, dof2), chi2.ppf(0.99, dof2), 100) xu3 = np.linspace(chi2.ppf(0.01, dof3), chi2.ppf(0.99, dof3), 100) xu4 = np.linspace(chi2.ppf(0.01, dof4), chi2.ppf(0.99, dof4), 100) xu5 = np.linspace(chi2.ppf(0.01, dof5), chi2.ppf(0.99, dof5), 100) xu6 = np.linspace(chi2.ppf(0.01, dof6), chi2.ppf(0.99, dof6), 100) xu7 = np.linspace(chi2.ppf(0.01, dof7), chi2.ppf(0.99, dof7), 100) xu8 = np.linspace(chi2.ppf(0.01, dof8), chi2.ppf(0.99, dof8), 100) xu9 = np.linspace(chi2.ppf(0.01, dof9), chi2.ppf(0.99, dof9), 100) xu10 = np.linspace(chi2.ppf(0.01, dof10), chi2.ppf(0.99, dof10), 100) xu11 = np.linspace(chi2.ppf(0.01, dof11), chi2.ppf(0.99, dof11), 100) xu12 = np.linspace(chi2.ppf(0.01, dof12), chi2.ppf(0.99, dof12), 100) ax.plot(xu/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $8< \log (M/M_{\odot})<9$, g-r=1') ax.plot(xu1/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $9< \log (M/M_{\odot})<10$, g-r=1') ax.plot(xu2/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $9< \log (M/M_{\odot})<10$, g-r=2') ax.plot(xu3/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $9< \log (M/M_{\odot})<10$, g-r=3') ax.plot(xu4/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $10< \log (M/M_{\odot})<11$, g-r=1') ax.plot(xu5/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $10< \log (M/M_{\odot})<11$, g-r=2') ax.plot(xu6/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $10< \log (M/M_{\odot})<11$, g-r=3') ax.plot(xu7/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $11< \log (M/M_{\odot})<12$, g-r=1') ax.plot(xu8/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $11< \log (M/M_{\odot})<12$, g-r=2') ax.plot(xu9/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $11< \log (M/M_{\odot})<12$, g-r=3') ax.plot(xu10/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ $11< \log (M/M_{\odot})<12$, g-r=4') ax.plot(xu11/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ reduced UGC11680NED01 PDF') ax.plot(xu12/df, chi2.pdf(x, df), lw=3, label='$\chi^2$ AGNs') ax.plot(x/df, chi2.pdf(x, df), 'k--', lw=3, label='Perfect Fit')
# import needed libraries import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.axes as ax import pylab # change to proper directory os.chdir('C:\Users\Matt\Desktop\Python Projects\Exploratory Data Analysis') # load file, select proper date range, convert row to numeric dtypes hpc = pd.read_csv('household_power_consumption.txt', sep=';', index_col=['Date'], usecols=['Global_active_power', 'Date']) # hpc = hpc.drop(['Date', 'Time'], axis=1).set_index('DT') hpc = hpc['1/2/2007':'3/2/2007'].convert_objects(convert_numeric=True) hpc = hpc[0:2881] # create plotting variables x = pd.date_range('2/1/2007', '2/3/2007 00:00', freq='T') y = hpc['Global_active_power'] #plt.plot(y, color='k') fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(x, y, color='k') ax.set_xticklabels(['Thur', '', '', '', 'Fri', '', '', '','Sat']) ax.set_yticklabels(['0', '', '2', '', '4', '', '6']) #plt.xlabel('Global Active Power (kilowatts)') ax.set_ylabel('Global Active Power (kilowatts)') #plt.title('Global Active Power') pylab.show()
return new elif self.m == other.n: return other * self else: raise ValueError( "Cannot multiply two matrices of incompatable dimensions") if __name__ == "__main__": fig = plt.figure() ax = fig.add_subplot(111) ax.plot([-10, 10], [0, 0], "b--") ax.plot([0, 0], [-10, 10], "b--") v3 = Vector(6, 6) x = 31 / 180 rm = Matrix([cos(x), sin(x)], [-sin(x), cos(x)]) print(rm) v3.plot(figure=ax) colours = ["black"] v4 = v3 * rm
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.axes as ax import pylab # change to proper directory os.chdir('C:\Users\Matt\Desktop\Python Projects\Exploratory Data Analysis') # load file, select proper date range, convert row to numeric dtypes hpc = pd.read_csv('household_power_consumption.txt', sep=';', index_col=['Date'], usecols=['Global_active_power', 'Date']) # hpc = hpc.drop(['Date', 'Time'], axis=1).set_index('DT') hpc = hpc['1/2/2007':'3/2/2007'].convert_objects(convert_numeric=True) hpc = hpc[0:2881] # create plotting variables x = pd.date_range('2/1/2007', '2/3/2007 00:00', freq='T') y = hpc['Global_active_power'] #plt.plot(y, color='k') fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(x, y, color='k') ax.set_xticklabels(['Thur', '', '', '', 'Fri', '', '', '', 'Sat']) ax.set_yticklabels(['0', '', '2', '', '4', '', '6']) #plt.xlabel('Global Active Power (kilowatts)') ax.set_ylabel('Global Active Power (kilowatts)') #plt.title('Global Active Power') pylab.show()
for index, x in enumerate(tamañosC2): npArray = np.array(tamañosC2[x]) #tamañosC0[x] = tamañosC0[x].mean() resC2.append(tamañosC2[x].mean()) yTicks.append(tamañosC2[x].mean()) for index, x in enumerate(tamañosC3): npArray = np.array(tamañosC3[x]) #tamañosC0[x] = tamañosC0[x].mean() resC3.append(tamañosC3[x].mean()) yTicks.append(tamañosC3[x].mean()) with PdfPages('ImagenFantasma_C_vs_ASM.pdf') as pdf: fig, ax = plt.subplots() ax.plot(tamaños, resASM, label="ASM original", marker=".") ax.plot(tamaños, resC0, label="C0", marker=".") ax.plot(tamaños, resC2, label="ASM 2px", marker=".") ax.plot(tamaños, resC3, label="C3", marker=".") ax.legend(['ASM original', 'O0', 'ASM 2px', 'O3'], loc='upper left') plt.xlabel("Cantidad de pixeles") plt.ylabel("Ciclos de clock") plt.title("Imagen Fantasma") #ax.set_xTicks = ['512','2048','8192','32768','120000','131072','480000','1920000'] #ax.set_yTicks = [str(yTicks[i]) for i in range(0, len(yTicks))] ax.ticklabel_format(style='plain') ax.axis([0, 2000000, 0, 180000000]) plt.grid(linestyle='-', linewidth=1) for tick in ax.get_xticklabels(): tick.set_rotation(55) #plt.show()
if len(resY3): plt.plot(resx3, resY3) if len(resY4): plt.plot(resx4, resY4) (supX1, supY1, supX2, supY2, supX3, supY3, supX4, supY4, supSlope) = computeSupportLines(low, timestamp) plt.plot(supX1, supY1) plt.plot(supX2, supY2) if len(supY3): plt.plot(supX3, supY3) if len(supY4): plt.plot(supX4, supY4) sys, resYs = [supY1, supY3, supY4], [resY1, resY3, resY4] (supYmVal, ascDescVal, riseFallVal, avgTouches) = detectTriangle([supY1, supY3, supY4], [resY1, resY3, resY4], high, low) mins, maxs = computePivotPoints(high, low, timestamp) for x, y in maxs: ax.plot(x, y) for x, y in mins: ax.plot(x, y) ax.xaxis.set_major_locator(mticker.MaxNLocator(10)) plt.ylim(ymin=min(low), ymax=max(high) + max(high) * 0.05) ax.grid(True) plt.yscale('log') plt.xlabel('Date') plt.ylabel('Price') plt.title(args.symbol) plt.show()
def imshow(self, *args, show_crosshair=True, show_mask=True, show_qscale=True, axes=None, invalid_color='black', mask_opacity=0.8, show_colorbar=True, **kwargs): """Plot the matrix (imshow) Keyword arguments [and their default values]: show_crosshair [True]: if a cross-hair marking the beam position is to be plotted. show_mask [True]: if the mask is to be plotted. show_qscale [True]: if the horizontal and vertical axes are to be scaled into q axes [None]: the axes into which the image should be plotted. If None, defaults to the currently active axes (returned by plt.gca()) invalid_color ['black']: the color for invalid (NaN or infinite) pixels mask_opacity [0.8]: the opacity of the overlaid mask (1 is fully opaque, 0 is fully transparent) show_colorbar [True]: if a colorbar is to be added. Can be a boolean value (True or False) or an instance of matplotlib.axes.Axes, into which the color bar should be drawn. All other keywords are forwarded to plt.imshow() or matplotlib.Axes.imshow() Returns: the image instance returned by imshow() """ if 'aspect' not in kwargs: kwargs['aspect'] = 'equal' if 'interpolation' not in kwargs: kwargs['interpolation'] = 'nearest' if 'origin' not in kwargs: kwargs['origin'] = 'upper' if show_qscale: ymin, xmin = self.pixel_to_q(0, 0) ymax, xmax = self.pixel_to_q(*self.shape) if kwargs['origin'].upper() == 'UPPER': kwargs['extent'] = [xmin, xmax, -ymax, -ymin] else: kwargs['extent'] = [xmin, xmax, ymin, ymax] bcx = 0 bcy = 0 else: bcx = self.header.beamcenterx bcy = self.header.beamcentery xmin = 0 xmax = self.shape[1] ymin = 0 ymax = self.shape[0] if kwargs['origin'].upper() == 'UPPER': kwargs['extent'] = [0, self.shape[1], self.shape[0], 0] else: kwargs['extent'] = [0, self.shape[1], 0, self.shape[0]] if axes is None: axes = plt.gca() ret = axes.imshow(self.intensity, **kwargs) if show_mask: # workaround: because of the colour-scaling we do here, full one and # full zero masks look the SAME, i.e. all the image is shaded. # Thus if we have a fully unmasked matrix, skip this section. # This also conserves memory. if (self.mask == 0).sum(): # there are some masked pixels # we construct another representation of the mask, where the masked pixels are 1.0, and the # unmasked ones will be np.nan. They will thus be not rendered. mf = np.ones(self.mask.shape, np.float) mf[self.mask != 0] = np.nan kwargs['cmap'] = matplotlib.cm.gray_r kwargs['alpha'] = mask_opacity kwargs['norm'] = matplotlib.colors.Normalize() axes.imshow(mf, **kwargs) if show_crosshair: ax = axes.axis() # save zoom state axes.plot([xmin, xmax], [bcy] * 2, 'w-') axes.plot([bcx] * 2, [ymin, ymax], 'w-') axes.axis(ax) # restore zoom state axes.set_axis_bgcolor(invalid_color) if show_colorbar: if isinstance(show_colorbar, matplotlib.axes.Axes): axes.figure.colorbar( ret, cax=show_colorbar) else: # try to find a suitable colorbar axes: check if the plot target axes already # contains some images, then check if their colorbars exist as # axes. cax = [i.colorbar[1] for i in axes.images if i.colorbar is not None] cax = [c for c in cax if c in c.figure.axes] if cax: cax = cax[0] else: cax = None axes.figure.colorbar(ret, cax=cax, ax=axes) axes.figure.canvas.draw() return ret
# Store the new solution uvalues = list(unext) return line, text #running the animation ---------------------------------------------------------------------------- if animate == True: # Preparing the plots fig, ax = plt.subplots() line_ini = ax.plot(x, uvalues, 'r') line, = ax.plot(x, uvalues) plt.title("Soliton propagation") plt.text(max(x) - 20, max(uvalues), r'alpha = {:3.2}'.format(alpha)) text = plt.text(10, max(uvalues), r't = {}'.format(0.0)) plt.xlabel('x (m)') plt.ylabel('u') # Start the animation (and therefore the calculation)
if t > xsize: # Scroll to the left. ax.set_xlim(t - xsize, t) line.set_data(xdata, ydata) return line, def on_close_figure(event): sys.exit(0) data_gen.t = -1 fig = plt.figure() fig.canvas.mpl_connect('close_event', on_close_figure) ax = fig.add_subplot(111) line, = ax.plot(label=lines, linestyle='-.', lw=5, color='red') ax.set_ylim(0, 300) ax.set_xlim(0, xsize) ax.grid() xdata, ydata = [], [] # Important: Although blit=True makes graphing faster, we need blit=False to prevent # spurious lines to appear when resizing the stripchart. ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=100, repeat=False) plt.show()
#ax.set_axisbelow(True) mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure(1) ax = fig.gca(aspect='equal', projection='3d') theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100) r = z**2 + 1 x = r * np.sin(theta) y = r * np.cos(theta) ax.plot(r_ECI[:, 0] / 1000, r_ECI[:, 1] / 1000, r_ECI[:, 2] / 1000, label='Orbital Position', color='k') # Sphere to represent Earth # Make data u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x1 = rEarth / 1000 * np.outer(np.cos(u), np.sin(v)) y1 = rEarth / 1000 * np.outer(np.sin(u), np.sin(v)) z1 = rEarth / 1000 * np.outer(np.ones(np.size(u)), np.cos(v)) # Plot the surface ax.plot_surface(x1, y1, z1, cmap='GnBu') # Legend and labels ax.legend()
if __name__ == '__main__': fig = pyplot.figure() axes = pyplot.subplot(111, projection='3d') points = [( 0.07826526, -0.8631922 , -0.49877228), (-0.02999477, -0.96742597, -0.25137087), ( 0.06420691, -0.9818318 , -0.17856034), ( 0.16057571, -0.95586931, -0.24602703), ( 0.24508727, -0.95988891, -0.13618192), ( 0.40681028, -0.88751077, -0.21640245), ( 0.44190865, -0.81611357, -0.37239145), ( 0.47401636, -0.79000325, -0.38884876), ( 0.07826526, -0.8631922 , -0.49877228)] axes.plot(*[[p[i] for p in points] for i in range(3)], color='r') query = (0.29210493879571187, -0.8867057671346513, -0.35836794954530027) axes.scatter(*[[query[i]] for i in range(3)], color='g') ext = (-0.21032302, 0.93088621, 0.29868896) axes.scatter(*[[ext[i]] for i in range(3)], color='g') for span in [[(0.47401636, -0.79000325, -0.38884876), (0.07826526, -0.8631922, -0.49877228)], [(-0.02999477, -0.96742597, -0.25137087), (0.06420691, -0.9818318, -0.17856034)]]: axes.plot(*[[p[i] for p in span] for i in range(3)], color='b') for isect in ((-0.38326894491900027, 0.8212662350427856, 0.4226425050078664), (0.38326894491900027, -0.8212662350427856, -0.4226425050078664)):