def word_cloud(words, caption=None, output_fp=None, random_state=None, width=400, height=200, **wordcloud_kwargs): """Word cloud for texts.""" # create word cloud text text = " ".join(str(word) for word in words) # generate word cloud images wordcloud = WordCloud(stopwords=STOPWORDS, max_words=100, random_state=random_state, background_color="white", width=width, height=height, **wordcloud_kwargs).generate(text) # render plot plt.figure(figsize=(width / DPI, height / DPI)) plt.imshow(wordcloud, interpolation="bilinear") if caption: plt.set_title(caption) plt.axis("off") # save or show if output_fp: plt.tight_layout(pad=1) plt.savefig(output_fp, dpi=100) else: plt.show()
def plot_horizontal_bar_from_cm(confusion_matrix = None, classes = []): # plt.rcdefaults() # plt.subplots(figsize = (10, 30)) width = 0.30 # Example data y_lables = 12 * ['a', 'b', 'c', 'd'] y_pos = list(range(len(y_lables))) print(y_pos) true_positives = 12 * [8.84036186, 12.94095337, 11.19919226, 10.64395389] false_negatives = 12 * [1, 1, 1, 1] false_positives = 12 * [2, 13, 13, 3] TP = plt.barh(y_pos, true_positives, width, color = 'green', label = 'TP') FN = plt.barh(y_pos, false_negatives, width, label = 'FN', left = TP) plt.barh(y_pos, false_positives, width, label = 'FP', left = FN) # ax.barh([p + width for p in y_pos], false_negatives, width, label = 'FN') # ax.barh([p + width * 2 for p in y_pos], false_positives, width, label = 'FP') plt.set_yticks([p + 1.5 * width for p in y_pos]) plt.set_yticklabels(y_lables) plt.invert_yaxis() # labels read top-to-bottom plt.set_xlabel('Performance') plt.set_title('How fast do you want to go today?') plt.legend(['TP', 'FN', 'FP'], loc = 'upper right') plt.show()
def drawPRC(result, sp, methodlabel): ''' Accept a result dataframe whose 'cond' coulmn is binary series representing the ture condition and 'pred' column is the normalized score of predicton. ''' print("drawing prc curve...") sp.set_xlabel('Recall') sp.set_ylabel('Precision') sp.set_ylim([0.0, 1.0]) sp.set_xlim([0.0, 1.0]) sp.set_title('2-class Precision-Recall curve') precision, recall, threshold = precision_recall_curve( result['cond'], result['pred']) average_precision = average_precision_score(result['cond'], result['pred']) myauc = auc(recall, precision) step_kwargs = ({ 'step': 'post' } if 'step' in signature(sp.fill_between).parameters else {}) sp.step(recall, precision, alpha=0.2, where='post') sp.fill_between(recall, precision, alpha=0.2, label=methodlabel + " (AUC = %.3f)" % myauc, **step_kwargs) return myauc
def plot_graph(self): self.ui.tempGraph.plot(self.idx_list, self.temp_list) plt = self.ui.tempGraph.canvas.ax self.ui.tempGraph.canvas.clear() plt.set_xlabel('Latest 10 values') if self.mode == "C": plt.set_ylabel('Temperature (Celsius)') plt.set_title('Temperature') #| Average = {0:0.1f} deg C plt.savefig('Temperature.png' ) #Saves the plots to be pulled up on the HTML elif self.mode == "F": plt.set_ylabel('Temperature (Fahrenheit)') plt.set_title( 'Temperature' ) # | Average = {0:0.1f} deg F.format(self.avgT).format(self.avgT) self.ui.tempGraph.canvas.draw() self.ui.humGraph.plot(self.idx_list, self.hum_list) plt2 = self.ui.humGraph.canvas.ax self.ui.humGraph.canvas.clear() plt2.set_xlabel('Latest 10 values') plt2.set_ylabel('Humidity (%)') plt2.set_title('Humidity') #| Average = {0:0.1f} %.format(self.avgH) plt2.savefig( 'Humidity.png') #Saves the plots to be pulled up on the HTML self.ui.humGraph.canvas.draw()
def plot_line(self, plt, data, kind, title, xlabel, ylabel): plt.set_title(title) plt.set_xlabel(xlabel) plt.set_ylabel(ylabel) plt.plot(data["data"], kind, linewidth=1) return plt pass
def plot_bar_pdf(self): """Function to plot the data and a plot of the probability density function along the same range Args: n_spaces (int): number of data points Returns: list: x values for the pdf plot list: y values for the pdf plot """ x = [] y = [] # calculate the x values to visualize for k in range(self.n + 1): x.append(k) y.append(self.pdf(k)) # make the plots plt.bar(x, y) plt.set_title('Binomial Distribution for \n Sample with p probability') plt.set_ylabel('Probability') plt.set_xlabel('Outcome') plt.show() return x, y # write a method to output the sum of two binomial distributions. Assume both distributions have the same p value. """Function to add together two Binomial distributions with equal p
def plotHistogram(graph_number, weight_range, optimizer, weight_decay): weights_histogram_small = small_batch_weights_by_graph_number[graph_number] weights_histogram_big = big_batch_weights_by_graph_number[graph_number] #plot a histogram of the weights fig, plt = subplots() plt.hist(weights_histogram_small, bins=number_bins, range=weight_range, facecolor='blue', alpha=0.5, label=str(small_batch_size)) plt.hist(weights_histogram_big, bins=number_bins, range=weight_range, facecolor='orange', alpha=0.5, label=str(big_batch_size)) #set axis labels and titles plt.set_xlabel('Weight Bins') plt.set_ylabel('Number of Weights') plt.set_title('Histogram of Weights for Configuration' + str(optimizer) + ', WD = ' + str(weight_decay)) #obtain min and max values of tuple mi, mx = weight_range #set axis limits plt.set_xlim([mi, mx]) plt.set_ylim([0, 5000000]) plt.legend(loc='upper right')
def show_line_chart_for_pr_rejection_rates_over_time( pulls, based_on_devstats_data=False, companies=[]): pulls = pulls.dropna(subset=["created_at", "closed_at"]) if based_on_devstats_data: pulls = p.determine_company_for_issues_with_history(pulls) pulls['company'] = np.where(pulls['company'].isin(companies), pulls['company'], 'unknown') else: users = c.get_issue_authors_with_company("kubernetes", "kubernetes") pulls = p.merge_issues_with_company_column(pulls, users) pulls["company"].fillna("others", inplace=True) pulls = p.add_dummy_column_for_rounded_year(pulls) # pulls = p.add_dummy_column_for_month(pulls) pulls = p.add_dummy_column_for_pr_merge_state(pulls) # companies = set(pulls["company"].values) # _normalized_stacked_chart(pulls, "company", "month", "line") df = pulls.groupby(["company", "year"])["pr_is_merged"].mean().unstack(level=0) print(df) plt = df.plot(kind="line") plt.set_ylabel("acceptance rate") plt.set_title("PR Acceptance Rate over the Community Lifetime", fontsize=10)
def GC_coverage_plot(file_name, GC_list, coverage_list, cover_list_fit): """ Args: file_name: str; absolute path of "GC_coverage.txt" GC_list: list; a list contains the defined GC range (0-100%) coverage_list: list; a list contains the normalized read count corresonding to its GC content cover_list_fit: list; a list contains the fitted number of coverage """ import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages plt.style.use('ggplot') fig = plt.figure() fig.patch.set_alpha(0.5) plt = fig.add_subplot(111) plt.patch.set_alpha(0.5) plt.plot(GC_list, coverage_list, 'o', color='b') plt.plot(GC_list, cover_list_fit, color='r', lw=2) plt.set_xlabel("GC content %") plt.set_ylabel("Normalized read count") plt.set_title("GC content - Normalized read count") file_path = "" if '/' in file_name: file_path = '/'.join(file_name.split('/')[:-1]) + '/' else: file_path = "./" pdf_save_path = file_path + "GC_coverage.pdf" pdf_save = PdfPages(pdf_save_path) pdf_save.savefig() pdf_save.close() print "GC coverage bias relationship plot saved in %s." % pdf_save_path
def plot_result_individual(edge_img, gene_name, output_file): """ This function plots the individual gene convolved result. """ edge_imgplot = plt.imshow(edge_img, cmap=plt.cm.gray) plt.set_title(f'{gene_name} Edge Convolved Image') plt.savefig(output_file)
def _draw_resource( plt: "matplotpib.axes.Axes", # type: ignore # noqa: F821 xaxis: List[float], reports: List[PerformanceReport], resources_range: List[int], title: str, ) -> None: """ Draw a plot for specific resource. :param plt: a subplot to draw on :param xaxis: list of values for x axis :param reports: performance reports to get values from :param resources_range: list of resource ids in performance.resource list to draw values for :param title: title for chart. :return: None """ for r in resources_range: res = reports[0].resources[r] label = res.name plt.plot(xaxis, [i.resources[r].value for i in reports], label=label) plt.set_ylabel(res.unit) plt.set_title(title) plt.legend()
def MovingAverageFilter(self, plot=False): """ Moving average of squared data. Class Returns ------------- v_int : ndarray Moving average resulting signal t_int : ndarray Timestamps for resulting average signal """ #number of samples to use for moving average window #window width in seconds/timestep N = int(round((self.iaw / 1000) / self.dt)) cs = np.cumsum(np.insert(self.v_sq, 0, 0)) self.v_int = (cs[N:] - cs[:-N]) / N self.t_int = self.t_der[N - 1:] #append 0s in places where arrays were shortened self.v_int = np.append([0] * (N + 1), self.v_int) self.v_int = np.append(self.v_int, [0, 0]) self.v_der = np.append([0] * 2, self.v_der) self.v_der = np.append(self.v_der, [0] * 2) if plot == True: pl.figure(figsize=(9, 5)) pl.plot(self.t_int, self.v_int, label='Moving Average') pl.legend() pl.xlabel('Time [s]') pl.set_title('Moving average filter')
def disp_reg_hist(location, title=None, show=False, train_num=0): """ Purpose : Plot the validation and training loss history for a regression output Args: location ... output directory containing log files title ... the title for the plot show ... if true then display figure, otherwise return figure train_num ... the number of the log_train file from output directory """ val_log = location + '/log_val.csv' train_log = location + '/log_train_' + str(train_num) + '.csv' val_log_df = pd.read_csv(val_log) train_log_df = pd.read_csv(train_log) plt.yscale("log") plt.plot(train_log_df.epoch, train_log_df.loss, 'g', label='Training loss') plt.plot(val_log_df.epoch, val_log_df.loss, 'b', label='Validation loss') if title is not None: plt.set_title(title, fontsize=20) else: plt.title('Training and Validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() if show: plt.grid() plt.show() return else: plt.savefig(location + '/loss_vs_epochs.png')
def setup_plot(title=None, x_label=None, y_label=None, log=[]): """ A function which prepares everything for a plot: sets title and labels and changes to logarithmic scale if required. """ # set some parameters for the legend, as it would be # to big else rcParams['font.size'] = 8 # the lines may be a bit wider than the default rcParams['lines.linewidth'] = 2 if title is not None: set_title(str(title), fontsize='large') if x_label is not None: xlabel(x_label) if y_label is not None: ylabel(y_label) if log != []: for lg in log: if lg in ['x', 1, '1']: xscale('log') if lg in ['y', 'z', 2, '2']: yscale('log')
def setup_plot( title = None, x_label = None, y_label = None, log = []): """ A function which prepares everything for a plot: sets title and labels and changes to logarithmic scale if required. """ # set some parameters for the legend, as it would be # to big else rcParams['font.size'] = 8 # the lines may be a bit wider than the default rcParams['lines.linewidth'] = 2 if title is not None: set_title(str(title), fontsize = 'large') if x_label is not None: xlabel(x_label) if y_label is not None: ylabel(y_label) if log != []: for lg in log: if lg in ['x', 1, '1']: xscale('log') if lg in ['y', 'z', 2, '2']: yscale('log')
def eb1(): fig = Figure() plt=fig.subplots() #plt = fig.add_subplot(1, 1, 1) plt.set_title("Expenditure - allocation") plt.set_xlabel("Worth") a=session['e'] c=session['nc'] a=np.arange(len(a)) w=0.25 c=[x + w for x in a] print(c) print(a) b=['raw goods', 'hr', 'tax', 'marketing', 'techn-cost'] b1=np.arange(len(a)) b2=[x + w for x in b1] plt.bar(b1,a, color="yellow", width=0.25, label="allocation") plt.bar(b2,c, color="green", width=0.25, label="expenditure") canvas = FigureCanvas(fig) output = io.BytesIO() canvas.print_png(output) response = make_response(output.getvalue()) response.mimetype = 'image/png' return response
def draw_histo(df, col_name, x_start, bin_width, n_bins, title, output_dir, output_filename): """ Create a histogram from a pandas dataframe column Args: df: a Pandas dataframe col_name: a string giving the column from the dataframe you'd like to plot x_start: the leftmost x-value in your plot bin_width: the desired width of your histogram bins n_bins: the desired number of histogram bins title: a string giving the title to be printed on your plot output_dir: the directory to write your output images to output_filename: the name you'd like to give the png output image """ plt = df[col_name].plot.hist( bins=[bin_width * (x + 0.5) + x_start for x in np.arange(0, n_bins)], edgecolor='black', color='#88d498') plt.set_title(title) print(col_name + ' max: ' + str(df[col_name].max()) + ', min: ' + str(df[col_name].min())) plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 3)) plt.get_figure().savefig(os.path.join(output_dir, output_filename)) plt.get_figure().clf()
def plotSolnAndGrad(self, plt, solVec, title=""): plt.set_title(title) # plt.set_xlabel('x',size=14,weight='bold') # plt.set_ylabel('y',size=14,weight='bold') plt.set_aspect('equal') plt.set_xlim(-0.1, 5.1) plt.set_ylim(-0.1, 1.2) xy = np.asarray(self.mesh.vertices) tci = tri.CubicTriInterpolator(self.mesh.dtri, solVec) (Ex, Ey) = tci.gradient(self.mesh.dtri.x, self.mesh.dtri.y) E_norm = np.sqrt(Ex**2 + Ey**2) vals = plt.tricontourf(self.mesh.dtri, solVec, cmap="jet") plt.quiver(self.mesh.dtri.x, self.mesh.dtri.y, -Ex / E_norm, -Ey / E_norm, units='xy', scale=20., zorder=3, color='blue', width=0.002, headwidth=2., headlength=2.) return vals
def makePlotData(scaffold, snp_list, scaf_len, scaffold_name): ''' :param scaffold: :param snp_list: :param scaf_len: :return: ''' print "Plotting function initiated (4)" position_list = [] # This list is a list of the number of snps in each 10kb bin bins = int(scaf_len/10000) for i in range(bins): pos_list = [] for pos in snp_list: if int(pos) >= i*10000 and int(pos) <= (i+1)*10000: pos_list.append(pos) else: pass #print (pos_list) position_list.append(len(pos_list)) print "Data prepped for matplot (5)" xlist = [i+1 for i in range(len(position_list))] plt.subplots(figsize=(8, 16)) plt.plot(position_list, xlist, 'r-') plt.axis([0, 8502, 0, 760]) plt.set_ylabel('Number of SNPs') plt.set_xlabel('10kb bin') plt.set_title(scaffold_name) plt.show()
def Histo(self,std,stderr,P,orient='horizontal',xlabel='',ylabel=''): ''' Function that plot the histogramm of the distribution given in x imputs: -x is the distrib itself (array) -mean is the mean of the distrib (float) -sigma_mean : the error on the average (float) -std : the standard deviation (RMS) of the distribution (float) -stderr : the errot on the RMS (float) -P is the figure where the histogram will be plotted. -xylabel and y label are the name ofthe axis. ''' numBins = 20 plt.hist(self.X,numBins,color='blue',alpha=0.8,orientation=orient,label='average = ' + str("%.5f" % np.mean(self.X)) + '$\pm$' + str("%.5f" % self.MEANerr()) + '\n' + 'rms =' + str("%.5f" % self.rms()) + '$\pm$' +str("%.5f" % self.RMSerr())) if xlabel == '': plt.set_xlabel('number of SNe') else: plt.set_xlabel(xlabel) if ylabel == '': plt.set_ylabel('number of SNe') else: plt.set_ylabel(ylabel) plt.set_title('Residuals') plt.legend(bbox_to_anchor=(0.95, 1.0),prop={'size':10})
def sample_plot(): """ Sample""" plt.style.use('seaborn') dev_x = [25, 26, 27, 28] dev_y = [1, 2, 3, 4] colors = [300, 315, 270, 305] plt.scatter(dev_x, dev_y, s=100, c=colors, cmap='Reds', edgecolor='k', linewidth=1, label="sample variables") cbar = plt.colorbar() cbar.set_label('Temperature') plt.set_title("Sample Plot") plt.set_xlabel("x") plt.set_ylabel("y") plt.legend() plt.tight_layout() # ============================================================================= # Για την center of mass ΜΟΝΟ: # # t_start = 2 # plt.fill_between(dev_x,dev_y, t_start, where = (dev_x > t_start), alpha = 0.25) # # Γιατί δεν λειτουργεί το where?? # ============================================================================= #ERRORS y_errormin = [0.1, 0.2, 0.5, 0.1] y_errormax = [0.2, 0.4, 0.1, 0.9] y_error = [y_errormin, y_errormax] x_error = 0.5 plt.errorbar(dev_x, dev_y, yerr=y_error, xerr=x_error, fmt=' ', elinewidth=1, capsize=5, errorevery=1, capthick=1) plt.show() # sample_plot()
def plotkernelsample(k, xmin=0, xmax=3): xx = np.linspace(xmin, xmax, 300)[:, None] K = k.K(xx) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) cov = sess.run(K) plt.plot(xx, np.random.multivariate_normal(np.zeros(300), cov, 5).T) plt.set_title('Samples ' + k.__class__.__name__) plt.show()
def sizeplot(dataf): dataf = dataf.copy() plt_data = dataf["ml"] plt_data = prep_sizebplot(plt_data) plt = sns.barplot(x='year', y='size', data=plt_data, palette="Blues_d") plt.set_title('Number of households in simulation') fig = plt.get_figure() return fig
def PCA(X): from sklearn.decomposition import PCA pca = PCA() pca.fit(X) plt.plot(pca.singular_values_) plt.set_title('Singular Values of X') plt.set_ylabel("features rank") plt.set_xlabel("Singular Values") plt.savefig(r'C:\Users\funrr\Desktop\ML project\plots' + '\\PCA' + '.jpg', dpi=600)
def plot_spline(plt, a, b, c, d, x, y, title): plt.plot(x, y, '.') for i in range(len(x) - 1): start = x[i] end = x[i + 1] X = np.linspace(start, end, 50) Y = a[i] + b[i] * (X - x[i]) + c[i] * (X - x[i])**2 + d[i] * (X - x[i])**3 plt.plot(X, Y) plt.set_title(title)
def highpassPlot(originalData, filteredData, lowFreq = 500, highFreq = 7500,saveFig): fig = plt.figure() plt.plot(originalData, color = 'blue', label = 'Original') plt.plot(filteredData, color = 'red', label = 'Filtered') plt.set_title('High pass filtered data between {} and {} Hz'.format(lowFreq, highFreq)) plt.legend() plt.tight_layout() if savefig: fig.savefig('highpass-plot.png') return
def plotMesh(self, plt, title=""): plt.set_title("Mesh") # plt.set_xlabel('x',size=14,weight='bold') # plt.set_ylabel('y',size=14,weight='bold') plt.set_aspect('equal'); plt.set_xlim(-0.1,5.1); plt.set_ylim(-0.1,1.2); xy = np.asarray(self.mesh.vertices); vals=plt.triplot(xy[:,0],xy[:,1],self.mesh.elements,'b-',linewidth=0.5); return vals
def plot_data_with_inset_two_figures(plt, title="", data=[], linestyles=[], labels=[], x_label="", y_label="", legend_loc="lower right", plot_from=0, plot_to=-1, axins_loc=None, axins_axis_visible=True, axins_zoom_factor=25, axins_x_y_lims=[0, 0, -1, -1], axins_aspect=1500, inset_loc1=1, inset_loc2=2, output_path=None): """ If inset plot is not to be drawn, set axins_loc to None. If the highest and lowest thresholds in the inset plot are to be automatically determined, set y1, y2 to -1, -1. """ plot_to = plot_to if plot_to != -1 else len(data[0]) # Create a new figure with a default 111 subplot # fig, ax = plt.subplots() ax = plt # Plot the entire data for i in range(len(data)): ax.plot(range(plot_from, plot_to), data[i][plot_from:plot_to], linestyle=linestyles[i], label=labels[i]) plt.legend(loc=legend_loc) plt.set_ylabel(y_label) plt.set_xlabel(x_label) plt.set_title(title.upper()) # Decide to plot the inset plot or not if axins_loc is not None: # Create a zoomed portion of the original plot axins = zoomed_inset_axes(ax, axins_zoom_factor, loc=axins_loc) for i in range(len(data)): axins.plot(range(plot_from, plot_to), data[i][plot_from:plot_to], linestyle=linestyles[i], label=labels[i]) # specify the limits (four bounding box corners of the inset plot) x1, x2, y1, y2 = axins_x_y_lims # Automatically set the highest and lowest thresholds in the inset plot if (y1 == -1): y1 = min([min(dataset[x1:x2]) for dataset in data]) - 0.0005 y2 = max([max(dataset[x1:x2]) for dataset in data]) + 0.0005 axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) axins.set_aspect(axins_aspect) # plt.set_yticks(visible=axins_axis_visible) # plt.set_xticks(visible=axins_axis_visible) # Choose which corners of the inset plot the inset markers are attachted to mark_inset(ax, axins, loc1=inset_loc1, loc2=inset_loc2, fc="none", ec="0.6") # Save the figure if output_path is not None: plt.savefig(output_path)
def sub_training_plot(plt, df, cols, index_col= None, main='',xlabel='xname', ylabel='yname', ylims=None, xlims=None, iflegend= 1 ): x= df[index_col] if index_col else df.index for col in cols: plt.plot(x, df[col],'-', label=col) #plt.bar(x, df[col],width=2/4, label='fps' ) if ylims and len(ylims)== 2: # a tuple plt.set_ylim(ylims) if xlims and len(xlims)== 2: # a tuple plt.set_xlim(xlims) if iflegend: plt.legend(loc = 'best') plt.set_title(main, fontsize=11)
def histograms(data, xlabel=None, ylabel=None, title=None): """Return a div containing an histogram from the data.""" mpl_fig = plt.figure() plt.hist(data) if xlabel: plt.set_xlabel(xlabel) if ylabel: plt.set_ylabel(ylabel) if title: plt.set_title(title) return get_div_from_data(mpl_fig)
def plot_data(y, tx, feature): """plot the fitted curve.""" xval = tx[:, feature - 1] #Let first feature be numbered 1 plt.scatter(xval, y, color='b', s=12, facecolors='none', edgecolors='r') xvals = np.arange(min(xval) - 0.1, max(xval) + 0.1, 0.1) #tx = build_poly(xvals, degree) #f = tx.dot(weights) #ax.plot(xvals, f) plt.set_xlabel("x " + str(feature)) plt.set_ylabel("y") plt.set_title("y vs. feature # " + str(feature))
def plot_boxplots(data): """ :param data: :return: """ all_data = data.values labels = data.columns plt.boxplot(all_data) plt.set_title('box plot') plt.yaxis.grid(True) plt.set_xticks([y + 1 for y in range(len(all_data))]) plt.set_xlabel('feature') plt.set_ylabel('ylabel') plt.setp(xticks=[y + 1 for y in range(len(all_data))], xticklabels=labels) plt.show()
def add_numbers(): import datetime import StringIO import random import urllib from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter value = request.args.get('wordlist') typegraph = request.args.get('wordlist2') danish =[1,2,3,4,5] #fin='/home/danish/Desktop/'+value; df=pd.read_csv(value) xx=df.Time.tolist() yy=df.Output.tolist() if typegraph=="matplotlib" : fig=Figure() plt=fig.add_subplot(111) plt.plot(xx,yy) #plt.show() plt.set_title('sample graph') plt.set_xlabel('time') plt.set_ylabel('output') #fig.autofmt_xdate() canvas=FigureCanvas(fig) png_output = StringIO.StringIO() canvas.print_png(png_output) data = png_output.getvalue().encode('base64') data_url = 'data:image/png;base64,{}'.format(urllib.quote(data.rstrip('\n'))) graph_data =data_url else: graph = pygal.Line() graph.title = '% OUTPUT' graph.x_labels= xx text=yy graph.add('Python', text) graph.x_labels = text graph_data = graph.render_data_uri() return jsonify(result=graph_data)
get_ipython().magic('matplotlib inline') import matplotlib from sklearn import svm import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_csv("iris.csv") df.columns = ["sepal_length","sepal_width","petal_length","petal_width","kind"] df = df.loc[:98,'petal_length':'kind'] color_dict = { 'Iris-setosa':'333', 'Iris-versicolor':'222'} plt = df.plot(kind='scatter', x='petal_length', y='petal_width',color=[color_dict[i] for i in df['kind']]); plt.set_title("Basic SVM Example") # legend C = 1.0 # SVM regularization parameter svc = svm.SVC(kernel='linear', C=C) svc.fit(df.loc[:,'petal_length':'petal_width'], df["kind"]) print(svc.predict([[-0.8, -1]])) w = svc.coef_[0] print("coef"+str(w)) print(svc.support_vectors_) print(svc.support_)
def Plot(self): self.delPlot() listSalePlot = [] listLabel = [] listDate = [] tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] for i in range(len(tableau20)): r, g, b = tableau20[i] tableau20[i] = (r / 255., g / 255., b / 255.) if (len(self.listDimensionsPlot)) == 1 : listInDimensions = self.read_CSV_InDimensions(self.listHeadShow[0]) for i in range(len(listInDimensions)): filename = listInDimensions[i] listLabel.append(filename) ##เพิ่ม Date ตรงนี้ with open(""+str(self.listDatePlot[0])+str(filename)+str(self.listMeasuresPlot[0])+".csv", newline='') as f: reader = csv.reader(f) row1 = next(reader) row2 = next(reader) listSalePlot.append(row2) listDate = row1 elif (len(self.listDimensionsPlot)) == 0: for i in range(len(self.listInDimensionsPlot)): filename = self.listInDimensionsPlot[i] listLabel.append(filename) with open(""+str(self.listDatePlot[0])+str(filename)+str(self.listMeasuresPlot[0])+".csv", newline='') as f: reader = csv.reader(f) row1 = next(reader) row2 = next(reader) listSalePlot.append(row2) listDate = row1 print (listDate) print (listLabel) print (listSalePlot) canvasPlot = 0 print (len(self.canvas)) for plot in range(len(self.plotType)): self.canvas.append("canvas"+str(plot)) if (self.plotType[plot]=="Plot"): if (len(self.listMeasuresPlot)==1) and (len(self.listDatePlot)==1): f = Figure(figsize=(6, 5), dpi=80) f.set_facecolor("w") plt = f.add_subplot(111) for i in range(len(listSalePlot)): print (listSalePlot[i]) plt.plot(listDate,listSalePlot[i],lw=2.5,color=tableau20[i],label=listLabel[i]) minX = (int(min(listDate))) maxX = (int(max(listDate))) x = range(minX, (maxX+1)) plt.set_xticks(x) plt.set_xticklabels(listDate) plt.set_title(str(self.listMeasuresPlot[0])) plt.legend(loc='upper left', bbox_to_anchor=(0, 1),ncol=2, fancybox=True, shadow=True) self.canvas[plot] = FigureCanvasTkAgg(f, master=self.f2) self.canvas[plot].show() self.canvas[plot].get_tk_widget().place(x = 300*canvasPlot + 350, y = 10) self.canvas[plot]._tkcanvas.place(x = 300*canvasPlot + 350, y = 10) elif (self.plotType[plot]=="Pie"): if (len(self.listMeasuresPlot)==1) and (len(self.listDatePlot)==1): f = Figure(figsize=(6, 5), dpi=80) f.set_facecolor("w") plt = f.add_subplot(111) plt.set_title(str(self.listMeasuresPlot[0])) saleCounty = [] colors = [] for i in range(len(listSalePlot)): saleCountySum = 0 colors.append(tableau20[i]) for j in range(len(listSalePlot[i])): saleCountySum = saleCountySum + float(listSalePlot[i][j]) saleCounty.append(saleCountySum) print (saleCounty) plt.pie(saleCounty, labels=listLabel, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90) plt.axis('equal') self.canvas[plot] = FigureCanvasTkAgg(f, master=self.f2) self.canvas[plot].show() self.canvas[plot].get_tk_widget().place(x = 300*canvasPlot + 350, y = 10) self.canvas[plot]._tkcanvas.place(x = 300*canvasPlot + 350, y = 10) elif (self.plotType[plot]=="Bar"): if (len(self.listMeasuresPlot)==1) and (len(self.listDatePlot)==1): f = Figure(figsize=(6, 5), dpi=80) f.set_facecolor("w") plt = f.add_subplot(111) print (len(listDate)) width = 0.2 ind = np.arange(len(listDate)) for i in range(len(listSalePlot)): listSalePlot[i] = [float(j) for j in listSalePlot[i]] plt.bar(ind+(i*width),listSalePlot[i],width,color=tableau20[i],label=listLabel[i]) plt.set_xticks(ind+((width/2)*(len(listSalePlot)))) plt.set_xticklabels(listDate) plt.set_title(str(self.listMeasuresPlot[0])) plt.legend(loc='upper left', bbox_to_anchor=(0, 1),ncol=2, fancybox=True, shadow=True) self.canvas[plot] = FigureCanvasTkAgg(f, master=self.f2) self.canvas[plot].show() self.canvas[plot].get_tk_widget().place(x = 300*canvasPlot + 350, y = 10) self.canvas[plot]._tkcanvas.place(x = 300*canvasPlot + 350, y = 10) canvasPlot = canvasPlot + 1.5 self.plotTypeOlt.append(canvasPlot)
import numpy as np import matplotlib.pyplot as plt from pandas import DataFrame, Series fig, img = plt.subplots(1, 1) # img.plot(np.random.randn(100),color='red', # linestyle='dashed',marker='o') plt.plot(np.random.randn(100), color="red", label="Red One") plt.plot(np.random.randn(100), color="green", label="Green One") plt.plot(np.random.randn(100), color="blue", label="Blue One") plt.set_title("Colorful Lines", fontsize=20) plt.set_xlabel("Frequency Level", fontsize=18) plt.legend(loc="best") # img[0,2].plot([30,100,20,80,120],'ko--',color='purple') # img.scatter(np.random.randn(100),np.random.randn(100)*2,color='red')
def hist( lonp, latp, fname, tind="final", which="contour", vmax=None, fig=None, ax=None, bins=(40, 40), N=10, grid=None, xlims=None, ylims=None, C=None, Title=None, weights=None, Label="Final drifter location (%)", isll=True, binscale=None, ): """ Plot histogram of given track data at time index tind. Args: lonp,latp: Drifter track positions in lon/lat [time x ndrifters] fname: Plot name to save tind (Optional): Default is 'final', in which case the final position of each drifter in the array is found and plotted. Alternatively, a time index can be input and drifters at that time will be plotted. Note that once drifters hit the outer numerical boundary, they are nan'ed out so this may miss some drifters. which (Optional[str]): 'contour', 'pcolor', 'hexbin', 'hist2d' for type of plot used. Default 'hexbin'. bins (Optional): Number of bins used in histogram. Default (15,25). N (Optional[int]): Number of contours to make. Default 10. grid (Optional): grid as read in by inout.readgrid() xlims (Optional): value limits on the x axis ylims (Optional): value limits on the y axis isll: Default True. Inputs are in lon/lat. If False, assume they are in projected coords. Note: Currently assuming we are plotting the final location of each drifter regardless of tind. """ if grid is None: loc = "http://barataria.tamu.edu:8080/thredds/dodsC/NcML/txla_nesting6.nc" grid = inout.readgrid(loc) if isll: # if inputs are in lon/lat, change to projected x/y # Change positions from lon/lat to x/y xp, yp = grid.proj(lonp, latp) # Need to retain nan's since basemap changes them to values ind = np.isnan(lonp) xp[ind] = np.nan yp[ind] = np.nan else: xp = lonp yp = latp if fig is None: fig = plt.figure(figsize=(11, 10)) else: fig = fig background(grid) # Plot coastline and such if tind == "final": # Find final positions of drifters xpc, ypc = tools.find_final(xp, yp) elif isinstance(tind, int): xpc = xp[:, tind] ypc = yp[:, tind] else: # just plot what is input if some other string xpc = xp.flatten() ypc = yp.flatten() if which == "contour": # Info for 2d histogram H, xedges, yedges = np.histogram2d( xpc, ypc, range=[[grid.x_rho.min(), grid.x_rho.max()], [grid.y_rho.min(), grid.y_rho.max()]], bins=bins ) # Contour Plot XE, YE = np.meshgrid(op.resize(xedges, 0), op.resize(yedges, 0)) d = (H / H.sum()) * 100 # # from http://matplotlib.1069221.n5.nabble.com/question-about-contours-and-clim-td21111.html # locator = ticker.MaxNLocator(50) # if you want no more than 10 contours # locator.create_dummy_axis() # locator.set_bounds(0,1)#d.min(),d.max()) # levs = locator() con = fig.contourf(XE, YE, d.T, N) # ,levels=levs)#(0,15,30,45,60,75,90,105,120)) con.set_cmap("YlOrRd") if Title is not None: plt.set_title(Title) # Horizontal colorbar below plot cax = fig.add_axes([0.3725, 0.25, 0.48, 0.02]) # colorbar axes cb = fig.colorbar(con, cax=cax, orientation="horizontal") cb.set_label("Final drifter location (percent)") # Save figure into a local directory called figures. Make directory # if it doesn't exist. if not os.path.exists("figures"): os.makedirs("figures") fig.savefig("figures/" + fname + "histcon.png", bbox_inches="tight") elif which == "pcolor": # Info for 2d histogram H, xedges, yedges = np.histogram2d( xpc, ypc, range=[[grid.x_rho.min(), grid.x_rho.max()], [grid.y_rho.min(), grid.y_rho.max()]], bins=bins, weights=weights, ) # Pcolor plot # C is the z value plotted, and is normalized by the total number of # drifters if C is None: C = (H.T / H.sum()) * 100 else: # or, provide some other weighting C = (H.T / C) * 100 p = plt.pcolor(xedges, yedges, C, cmap="YlOrRd") if Title is not None: plt.set_title(Title) # Set x and y limits if xlims is not None: plt.xlim(xlims) if ylims is not None: plt.ylim(ylims) # Horizontal colorbar below plot cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) # colorbar axes cb = fig.colorbar(p, cax=cax, orientation="horizontal") cb.set_label("Final drifter location (percent)") # Save figure into a local directory called figures. Make directory # if it doesn't exist. if not os.path.exists("figures"): os.makedirs("figures") fig.savefig("figures/" + fname + "histpcolor.png", bbox_inches="tight") # savefig('figures/' + fname + 'histpcolor.pdf',bbox_inches='tight') elif which == "hexbin": if ax is None: ax = plt.gca() else: ax = ax if C is None: # C with the reduce_C_function as sum is what makes it a percent C = np.ones(len(xpc)) * (1.0 / len(xpc)) * 100 else: C = C * np.ones(len(xpc)) * 100 hb = plt.hexbin( xpc, ypc, C=C, cmap="YlOrRd", gridsize=bins[0], extent=(grid.x_psi.min(), grid.x_psi.max(), grid.y_psi.min(), grid.y_psi.max()), reduce_C_function=sum, vmax=vmax, axes=ax, bins=binscale, ) # Set x and y limits if xlims is not None: plt.xlim(xlims) if ylims is not None: plt.ylim(ylims) if Title is not None: ax.set_title(Title) # Want colorbar at the given location relative to axis so this works # regardless of # of subplots, so convert from axis to figure # coordinates. To do this, first convert from axis to display coords # transformations: # http://matplotlib.org/users/transforms_tutorial.html # axis: [x_left, y_bottom, width, height] ax_coords = [0.35, 0.25, 0.6, 0.02] # display: [x_left,y_bottom,x_right,y_top] disp_coords = ax.transAxes.transform( [(ax_coords[0], ax_coords[1]), (ax_coords[0] + ax_coords[2], ax_coords[1] + ax_coords[3])] ) # inverter object to go from display coords to figure coords inv = fig.transFigure.inverted() # figure: [x_left,y_bottom,x_right,y_top] fig_coords = inv.transform(disp_coords) # actual desired figure coords. figure: # [x_left, y_bottom, width, height] fig_coords = [ fig_coords[0, 0], fig_coords[0, 1], fig_coords[1, 0] - fig_coords[0, 0], fig_coords[1, 1] - fig_coords[0, 1], ] # Inlaid colorbar cax = fig.add_axes(fig_coords) # # Horizontal colorbar below plot # cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) # colorbar axes cb = fig.colorbar(hb, cax=cax, orientation="horizontal") cb.set_label(Label) # Save figure into a local directory called figures. Make directory # if it doesn't exist. if not os.path.exists("figures"): os.makedirs("figures") fig.savefig("figures/" + fname + "histhexbin.png", bbox_inches="tight") # savefig('figures/' + fname + 'histhexbin.pdf',bbox_inches='tight') elif which == "hist2d": plt.hist2d( xpc, ypc, bins=40, range=[[grid.x_rho.min(), grid.x_rho.max()], [grid.y_rho.min(), grid.y_rho.max()]], normed=True, ) plt.set_cmap("YlOrRd") # Set x and y limits if xlims is not None: xlim(xlims) if ylims is not None: ylim(ylims) # Horizontal colorbar below plot cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) # colorbar axes cb = fig.colorbar(cax=cax, orientation="horizontal") cb.set_label("Final drifter location (percent)") # Save figure into a local directory called figures. Make directory # if it doesn't exist. if not os.path.exists("figures"): os.makedirs("figures") fig.savefig("figures/" + fname + "hist2d.png", bbox_inches="tight")
# Need to remove 0 values in time_to_city and time_to_extinction. time_to_city = time_to_city[time_to_city != 0] time_to_extinction = time_to_extinction[time_to_extinction != 0] # Computing desired values and inserting into appropriate arrays. avg_time_to_city[i-1] = np.mean(time_to_city) avg_time_to_city[i-1] = np.mean(time_to_extinction) prob_inf_city[i-1] = infections/len(filenames) prob_extinct_city[i-1] = extinctions/len(filenames) # Create appropriate plots and save them # Plotting avg time for infection to reach city vs movement rate fig = plt.figure(figsize=(10, 7)) plt.set_title('Average Time for Infection to Reach City') plt.set_ylabel('Time') plt.set_xlabel('Mu') plt.scatter(mu_vals, avg_time_to_city) fig.saveas('timetoinf_vs_mu.png') # Plotting avg time to extinction vs movement rate fig = plt.figure(figsize=(10, 7)) plt.set_title('Average Time to Extinction') plt.set_ylabel('Time') plt.set_xlabel('Mu') plt.scatter(mu_vals, avg_time_to_extinction) fig.saveas('timetoextinct_vs_mu.png') # Plotting p(infection) in city vs movement rate fig = plt.figure(figsize=(10, 7))