def barGraph(xData, xAxis, yData, yAxis, titlePlot, c, width, legendAxis): #did not work together for some reason if len(xData) != np.shape(biomass)[0]: if len(xData) != np.shape(biomass)[1]: print "The number of species does not match the number of rows in the biomass data." fig, ax = plt.subplots() #There will be 3 different figures: ax, ay, az. - changed to just ax ind = np.arange(len(xData)) if len(xData) == np.shape(biomass)[0]: #to make second bar plot correctly, iterate through rows or columns? barsPerInput = np.shape(yData)[1] else: barsPerInput = np.shape(yData)[0] for barNumber in range(barsPerInput): if len(xData) == np.shape(biomass)[0]: plt.bar(ind + barNumber*width, biomass[:, barNumber], width, color = c[barNumber], label = legendAxis[barNumber]) else: plt.bar(ind + barNumber*width, biomass[barNumber, :], width, color = c[barNumber], label = legendAxis[barNumber]) plt.ylim(0.0, plt.ylim()[1]) #further define graph (keep below plotting lies) ax.set_xticks(ind + width) ax.set_xticklabels(xData) plt.legend() ax.set_xlabel(xAxis) ax.set_ylabel(yAxis) ax.set_title(titlePlot) plt.show() #plt.draw = show multiple figures at once
def barplot(grouped_df, _column, statistic, levels=[0]): means = grouped_df.groupby(level=levels).mean() bar_width = 1.0/(len(means.index)) error_config = {'ecolor': '0.1'} sems = grouped_df.groupby(level=levels).sem().fillna(0) fig = plt.figure() fig.set_size_inches(10,6) ax = fig.add_subplot(1,1,1) plt.bar(np.arange(0.1,(len(means.index)+0.1),1), means[_column].fillna(0), color= '#AAAAAA', yerr=sems[_column].fillna(0), error_kw=error_config, label=list(means.index)) if means[_column].values.min() >= 0: ax.set_ylim(0,1.1*((means[_column] + sems[_column]).values.max())) else: ax.set_ylim(1.1*((means[_column] - sems[_column]).values.min()),1.1*((means[_column] + sems[_column]).values.max())) ax.set_ylabel(statistic + ' ' + u"\u00B1" + ' SEM', fontsize=20) # +/- sign is u"\u00B1" ax.set_xticks(np.arange(0.1+bar_width/2.0,(len(means.index)+0.1+(bar_width/2.0)),1)) ax.set_xticklabels(list(means.index), rotation=90) ax.tick_params(axis='y', labelsize=16 ) ax.set_xlabel('Group', fontsize=20) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') return fig
def make_bar( x, y, f_name, title=None, legend=None, x_label=None, y_label=None, x_ticks=None, y_ticks=None, ): fig = plt.figure() if title is not None: plt.title(title, fontsize=16) if x_label is not None: plt.ylabel(x_label) if y_label is not None: plt.xlabel(y_label) if x_ticks is not None: plt.xticks(x, x_ticks) if y_ticks is not None: plt.yticks(y_ticks) plt.bar(x, y, align="center") if legend is not None: plt.legend(legend) plt.savefig(f_name) plt.close(fig)
def ExampleWithData(data, path): '''modified example from matplotlib gallery.''' # skip the uppermost levels as we have no # tracks or slices N = 5 ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars: can also be len(x) sequence p1 = plt.bar(ind, data["menMeans"], width, color='r', yerr=data["womenStd"]) p2 = plt.bar(ind, data["womenMeans"], width, color='y', bottom=data["menMeans"], yerr=data["menStd"]) plt.ylabel('Scores') plt.title('Scores by group and gender') plt.xticks(ind + width / 2., ('G1', 'G2', 'G3', 'G4', 'G5')) plt.yticks(np.arange(0, 81, 10)) plt.legend((p1[0], p2[0]), ('Men', 'Women')) # return a place holder for this figure return ResultBlocks( ResultBlock("#$mpl 0$#\n", ""), title="MyTitle")
def statistics_charts(self): if plt is None: return for chart in self.stats_charts: if chart["type"] == "plot": fig = plt.figure(figsize=(8, 2)) for xdata, ydata, label in chart["data"]: plt.plot(xdata, ydata, "-", label=label) plt.legend(loc="center left", bbox_to_anchor=(1, 0.5)) elif chart["type"] == "timeline": fig = plt.figure(figsize=(16, 2)) for i, (starts, stops, label) in enumerate(chart["data"]): plt.hlines([i] * len(starts), starts, stops, label=label) plt.ylim(-1, len(chart["data"])) elif chart["type"] == "bars": fig = plt.figure(figsize=(16, 4)) plt.bar(range(len(chart["data"])), chart["data"]) elif chart["type"] == "boxplot": fig = plt.figure(figsize=(16, 4)) plt.boxplot(chart["data"]) else: raise Exception("Unknown chart") png = serialize_fig(fig) yield chart["name"], html_embed_img(png)
def acf_plot_raw(type, date, lag=8, window=24, days=30): lag, window, days = int(lag), int(window), int(days) date = datetime.strptime(date, "%Y%m%d") target = int(buckify(window, date)) cc = CrashCounts(type, window) t, counts = cc.crash_counts() target = t.index(target) counts = counts[target-days:target+1] t = [i - 0.02 for i in xrange(1, lag)] a = acf(counts, lag) plt.title("Global crash count sample ACF plot") plt.xlabel("Lag") plt.ylabel("ACF") plt.bar(t, a, width=0.04) err = 2 / sqrt(days) plt.plot([0, lag+1], [err, err], "r--") plt.plot([0, lag+1], [-err, -err], "r--") plt.plot([0, lag+1], [0, 0], "k-") plt.xlim(0, lag) plt.show()
def make_overview_plot(filename, title, noip_arrs, ip_arrs): plt.title("Inner parallelism - " + title) plt.ylabel('Time (ms)', fontsize=12) x = 0 barwidth = 0.5 bargroupspacing = 1.5 for z in zip(noip_arrs, ip_arrs): noip,ip = z noip_mean,noip_conf = conf_stats(noip) ip_mean,ip_conf = conf_stats(ip) b_noip = plt.bar(x, noip_mean, barwidth, color='r', yerr=noip_conf, ecolor='black', alpha=0.7) x += barwidth b_ip = plt.bar(x, ip_mean, barwidth, color='b', yerr=ip_conf, ecolor='black', alpha=0.7) x += bargroupspacing plt.xticks([0.5, 2.5, 4.5], ['50k', '100k', '200k'], rotation='horizontal') fontP = FontProperties() fontP.set_size('small') plt.legend([b_noip, b_ip], \ ('no inner parallelism', 'inner parallelism'), \ prop=fontP, loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=2) plt.ylim([0,62000]) plt.savefig(output_file(filename)) plt.clf()
def graph_by_sender(self): mac_adresses = {} # new dictionary for pkt in self.pcap_file: mac_adresses.update({pkt[Dot11].addr2: 0}) for pkt in self.pcap_file: mac_adresses[pkt[Dot11].addr2] += 1 MA = [] for ma in mac_adresses: MA.append(mac_adresses[ma]) plt.clf() plt.suptitle('Number of packets of every sender', fontsize=14, fontweight='bold') plt.bar(range(len(mac_adresses)), sorted(MA), align='center', color=MY_COLORS) plt.xticks(range(len(mac_adresses)), sorted(mac_adresses.keys())) plt.rcParams.update({'font.size': 10}) plt.xlabel('Senders mac addresses') plt.ylabel('Number of packets') # Set tick colors: ax = plt.gca() ax.tick_params(axis='x', colors='k') ax.tick_params(axis='y', colors='r') ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45) plt.show()
def plot_top_candidates(tweets, n, gop, save_to = None): ''' Plots the counts of top n candidate pair mentions given a Tweets class. Note: used for task 2. ''' counts = tweets.top_pairs(n, gop) pairs = [] mentions = [] for pair, ment in counts: p = pair.split("|") c0 = CANDIDATE_NAMES[ p[0] ] c1 = CANDIDATE_NAMES[ p[1] ] pairs.append(c0 + "\n" + c1) mentions.append(ment) fig = plt.figure(figsize = (FIGWIDTH, FIGHEIGHT)) plt.bar(range(len(counts)), mentions) plt.xticks(range(len(counts)), pairs, rotation = 'vertical') if gop: plt.title("Pairs of GOP Candidates Mentioned most Frequently together") else: plt.title("Pairs of Candidates Mentioned most Frequently together") plt.xlabel("Number of Mentions") plt.ylabel("Number of Tweets") plt.show() if save_to: fig.savefig(save_to)
def main( args ): hash = get_genes_with_features(args['file']) for key, featurearray in hash.iteritems(): cluster, branch = key.split() length = int(featurearray[0][0]) import matplotlib.pyplot as P x = [e+1 for e in range(length+1)] y1 = [0] * (length+1) y2 = [0] * (length+1) for feature in featurearray: length, pos, aa, prob = feature[0:4] if prob > 0.95: y1[pos] = prob else: y2[pos] = prob P.bar(x, y1, color='#000000', edgecolor='#000000') P.bar(x, y2, color='#bbbbbb', edgecolor='#bbbbbb') P.ylim(ymin=0, ymax=1) P.xlim(xmin=0, xmax=length) P.xlabel("position in the ungapped alignment [aa]") P.ylabel(r'$P (\omega > 1)$') P.title(cluster + " (branch " + branch + ")") P.axhline(y=.95, xmin=0, xmax=length, linestyle=":", color="k") P.savefig(cluster + "." + branch + ".png", format="png") P.close()
def barPlot(self, datalist, threshold, figname): tally = self.geneCount(datalist) #Limit the items plotted to those over 1% of the read mass geneplot = defaultdict() for g, n in tally.iteritems(): if n > int(sum(tally.values())*threshold): geneplot[g] = n #Get plotting values olist = OrderedDict(sorted(geneplot.items(),key=lambda t: t[0])) summe = sum(olist.values()) freq = [float(x)/float(summe) for x in olist.values()] #Create plot fig = plt.figure() width = .35 ind = np.arange(len(geneplot.keys())) plt.bar(ind, freq) plt.xticks(ind + width, geneplot.keys()) locs, labels = plt.xticks() plt.setp(labels, rotation=90) plt.show() fig.savefig(figname) print("Saved bar plot as: "+figname)
def makePlot( k, counts, yaxis=[], width=0.8, figsize=[14.0,8.0], title="", ylabel='tmpylabel', xlabel='tmpxlabel', labels=[], show=False, grid=True, xticks=[], yticks=[], steps=5, save=False ): ''' ''' if not list(yaxis): yaxis = np.arange(len(counts)) if not labels: labels = yaxis index = np.arange(len(yaxis)) fig, ax = plt.subplots() fig.set_size_inches(figsize[0],figsize[1]) plt.bar(index, counts, width) plt.title(title) if not xticks: print ('Making xticks') ticks = makeTicks(yMax=len(yaxis),steps=steps) xticks.append(ticks+width/2.) xticks.append(labels) print ('Done making xticks') if yticks: print ('Making yticks') # plt.yticks([1,2000],[0,100]) plt.yticks(yticks[0],yticks[1]) # ax.set_yticks(np.arange(0,100,10)) print ('Done making yticks') plt.xticks(xticks[0]+width/2., xticks[1]) plt.ylabel(ylabel) plt.xlabel(xlabel) # ax.set_xticks(range(0,len(counts)+2)) fig.autofmt_xdate() # ax.set_xticklabels(ks) plt.axis([0, len(yaxis), 0, max(counts) + (max(counts)/100)]) plt.grid(grid) location = ROOT_FOLDER + "/../muchBazar/src/image/" + k + "distribution.png" if save: plt.savefig(location) print ('Distribution written to: %s' % location) if show: plt.show()
def screeplot(self, type="barplot", **kwargs): """ Produce the scree plot :param type: type of plot. "barplot" and "lines" currently supported :param show: if False, the plot is not shown. matplotlib show method is blocking. :return: None """ # check for matplotlib. exit if absent. try: imp.find_module('matplotlib') import matplotlib if 'server' in kwargs.keys() and kwargs['server']: matplotlib.use('Agg', warn=False) import matplotlib.pyplot as plt except ImportError: print "matplotlib is required for this function!" return variances = [s**2 for s in self._model_json['output']['importance'].cell_values[0][1:]] plt.xlabel('Components') plt.ylabel('Variances') plt.title('Scree Plot') plt.xticks(range(1,len(variances)+1)) if type == "barplot": plt.bar(range(1,len(variances)+1), variances) elif type == "lines": plt.plot(range(1,len(variances)+1), variances, 'b--') if not ('server' in kwargs.keys() and kwargs['server']): plt.show()
def plot_err_comp(): results = Control_results; fig, ax = plt.subplots() #results rects_train = plt.bar(ind,results['train_errs'], width, color = 'b', alpha = opacity, yerr =results['train_errs_std'], label = 'train'); rects_test = plt.bar(ind+width,results['test_errs'], width, color = 'r', alpha = opacity, yerr =results['test_errs_std'], label = 'test'); plt.xlabel('Datasets'); plt.ylabel('Error(MSE)'); plt.title('Performance (Error)') plt.xticks(ind+width, Datasets); plt.legend(); #plot and save plt.tight_layout(); plt.savefig('errs_comparison'+'.png'); plt.show();
def freq_bar_clicked(self): if not self.current_patient: QtGui.QMessageBox.about(self, 'Error', 'Pick a Patient!') all_sessions = [] freq_voltages = ''.join(self.freq_line_edit.text().split(' ')).split(',') freq_voltages = [float(v) for v in freq_voltages] print(self.current_patient.name) print(self.current_patient.sessions[0].freq_bc_scores, freq_voltages) if type(self.current_patient) == Patient: all_sessions = [s for s in self.current_patient.sessions if s.frequency_voltages == freq_voltages] else: for p in self.current_patient.patients: all_sessions += [s for s in p.sessions if s.frequency_voltages == freq_voltages] if not all_sessions: QtGui.QMessageBox.about(self, 'Error', 'No sessions that match these frequencies were found!') bc_counts = [0 for entry in freq_voltages] time_count = 0 for s in all_sessions: time_count += s.time for i, perc in enumerate(s.freq_bc_scores): bc_counts[i] += perc * s.time bc_percentages = [(count/time_count) * 100 for count in bc_counts] plt.figure() plt.title('CONVERGENCE SCORE FOR DIFFERENT FREQUENCIES') plt.bar(range(len(freq_voltages)), bc_percentages) plt.show()
def bar_graph_dict(dict_to_plot, plot_title="", xlab="", ylab="", log_scale=False, col="#71cce6", sort_key_list=None, min_count=1): """ Plots a bar graph of the provided dictionary. Params: dict_to_plot (dict): should have the format {'label': count} plot_title (str), xlab (str), ylab (str), log_scale (bool): fairly self-explanatory plot customization col (str): colour for the bars sort_key_list (list): the keys of the dictionary are assumed to match based its first item and reordered as such min_count (int): do not plot items with less than this in the count """ # Sort dictionary & convert to list using custom keys if needed if not sort_key_list: list_to_plot = sorted(dict_to_plot.items()) else: list_to_plot = sorted(dict_to_plot.items(), key=lambda x: sort_key_list.index(x[0])) # Remove list items with less than min_count if min_count != 1: list_to_plot = [dd for dd in list_to_plot if dd[1] >= min_count] # Bar plot of secondary structure regions containing mutants in each mutant Cas9 bar_width = 0.45 plt.bar(np.arange(len(list_to_plot)), [dd[1] for dd in list_to_plot], width=bar_width, align='center', color=col) plt.xticks(range(len(list_to_plot)), [dd[0] for dd in list_to_plot], rotation=45, ha='right') plt.title(plot_title) plt.xlabel(xlab) plt.ylabel(ylab) if log_scale: plt.yscale('log') plt.ylim(min_count-0.1) # Show values with just the minimum count plt.show()
def bar_plot(hist_mod, tool, paths, save_to=None, figsize=(10, 10), fontsize=6): """ Plots bar plot for selected tracks: :param figsize: Plot figure size :param save_to: Object for plots saving :param fontsize: Size of xlabels on plot """ ind = np.arange(len(paths)) result = [] for path in paths: result.append((donor(path), Bed(path).count())) result = sorted(result, key=donor_order_id) result_columns = list(zip(*result)) plt.figure(figsize=figsize) width = 0.35 plt.bar(ind, result_columns[1], width, color='black') plt.ylabel('Peaks count', fontsize=fontsize) plt.xticks(ind, result_columns[0], rotation=90, fontsize=fontsize) plt.title(hist_mod + " " + tool, fontsize=fontsize) plt.tight_layout() save_plot(save_to)
def singularplot(word,modelname,vector): xlocations = np.array(range(len(vector))) plt.bar(xlocations,vector) plot_title = word.split('_')[0]+'\n'+u'модель '+modelname plt.title(plot_title,fontproperties=font) plt.savefig(root+'static/singleplots/'+modelname+'_'+word.encode('ascii','backslashreplace')+'.png',dpi=150,bbox_inches='tight') plt.close()
def phrase_frequency_over_time(self, phrase, time_interval=1, time_unit="weeks", plot=False): msgs = self.find_all_instances_phrase(phrase) time_interval = intervals[time_unit] * time_interval start_date = to_timestamp( dateutil.parser.parse(self.data[-1]['date_time'])) end_date = to_timestamp( dateutil.parser.parse(self.data[1]['date_time'])) bin_edges = [i for i in xrange(start_date, end_date, time_interval)] hist = [0] * (len(bin_edges) - 1) for i in xrange(0, len(bin_edges) - 1): for msg in msgs: date = to_timestamp( dateutil.parser.parse(msg['date_time'])) if date > bin_edges[i] and date <= bin_edges[i+1]: hist[i] += 1 if plot: plt.title("Frequency count for phrase %s" % phrase) bin_edges = from_timestamp(bin_edges) plt.bar(bin_edges[:-1], hist, width=1) plt.show() return hist, bin_edges
def tagPicture(mp): val = [] label = [] lst0 = mp.keys() #print lst0 lst1 = mp.values() if len(lst1) > 10: num = 10 else: num = len(lst1) while (num != 0): i = lst1.index(max(lst1)) label.append(lst0[i]) #print type(lst1[i]) val.append(int(lst1[i])) lst0.pop(i) lst1.pop(i) num -= 1 #print label pos = np.arange(len(val)) +.5 plt.figure(1) plt.bar(pos,val,color='c',align='center') plt.xticks(pos,label) plt.ylabel(u'人数') string = u"热门标签" plt.title(string) plt.show()
def plot_pulbications_years(meta_data_folder): ## ## Retrieve the year of publications of all ## articles from the meta_data_folder and ## plot the histogramm of publications over ## the years ## ## TODO : add to bibotlite.py ## ## create the structure year_to_count = {} for meta_file in glob.glob(meta_data_folder+"/*.csv"): year = get_date_from_meta_save(meta_file) if(int(year) < 2018): if(year not in year_to_count.keys()): year_to_count[year] = 1 else: year_to_count[year] += 1 ## plot graphe plt.bar(year_to_count.keys(), year_to_count.values(), 1, color='b') plt.show()
def PlotGraph(wordcounts): #v=list(D.values()) print("Starting to plot a graph: ") plt.bar(range(len(wordcounts)), wordcounts.values(), align='center') plt.xticks(range(len(wordcounts)), list(wordcounts.keys())) plt.show()
def bar(x, h, color='#002299', show_stats=False, normed=False, fix_lim=True, log=False): """ plots a nice histogram. x, h: the histogram bins and histogram heights, as returned by np.histogram. color: color of the histogram bars show_stats: adds an infobox in a corner of the histogram displaying the average and standard deviation of the dist. normed: if True, the distribution will be normed so its integration gives 1. """ w = (x[1] - x[0]) * 0.8 delta = (x[1] - x[0]) * 0.1 if normed: h = 1. * h / np.sum(h) plt.bar(x[:-1] + delta, h, width=w, color=color, ec='none', log=log) if fix_lim: plt.xlim(np.min(x), np.max(x)) plt.ylim(0, np.max(h) * 1.1) ax = plt.gca() ax.yaxis.grid(True, color='white') if show_stats: props = dict(boxstyle='round', facecolor='wheat', alpha=0.7) normdist = h / h.sum() avg = np.sum(normdist * x[:-1]) ax.text(0.05, 0.95, '$\mu = %5.2f $' % avg, transform=ax.transAxes, va='top', bbox=props)
def plotPredictedOriginsTotals(oemfileWT,oemfileMUT): # Get the total number of predicted origins for WT compared against confirmed, likely, dubious origins totalPOcomparedWT = oc.getnumComparedOriginsWTMUT(oemfileWT,2500) # Get the total number of predicted origins for MUT against confirmed, likely, dubious origins totalPOcomparedMUT = oc.getnumComparedOriginsWTMUT(oemfileMUT,2500) originsConfirmed = [totalPOcomparedWT['C'],totalPOcomparedMUT['C']] originsLikely = [totalPOcomparedWT['L'],totalPOcomparedMUT['L']] originsDubious = [totalPOcomparedWT['D'],totalPOcomparedMUT['D']] originsNone = [totalPOcomparedWT['N'],totalPOcomparedMUT['N']] ind = np.arange(2) # the x locations for the groups width = 0.35 # the width of the bars: can also be len(x) sequence plt1 = plt.bar(ind, originsConfirmed, width, color='g') plt2 = plt.bar(ind, originsLikely, width, color='y',bottom=originsConfirmed) plt3 = plt.bar(ind, originsDubious, width, color='r',bottom=[originsConfirmed[j]+originsLikely[j] for j in range(len(originsConfirmed))]) plt4 = plt.bar(ind, originsNone, width, color='grey',bottom=[originsConfirmed[j]+originsLikely[j]+originsDubious[j] for j in range(len(originsConfirmed))]) plt.xticks(ind+width/2., ('WT', 'KO')) plt.legend((plt1,plt2,plt3,plt4),('Confirmed','Likely','Dubious','None'),loc='upper center') plt.ylabel('Number of Origins') plt.show()
def draw_bar_plot(self, dictlist, title, fid_x, fid_y1, fid_y2, fid_y3, y_min, y_max, legend1, legend2, legend3, outputfile, x_interval=1): ind = np.arange(len(dictlist)) x_ray = self.get_x_from_dictlist(dictlist, fid_x, x_interval) y_1 = self.get_int_list_from_dictlist(dictlist, fid_y1) y_2 = self.get_int_list_from_dictlist(dictlist, fid_y2) y_3 = self.get_int_list_from_dictlist(dictlist, fid_y3) plt.cla() width = 0.35 y_3_bottom = [] for i in range(len(y_1)): y_3_bottom.append(y_1[i] + y_2[i]) p1 = plt.bar(ind, y_1, width, color='r') p2 = plt.bar(ind, y_2, width, color='y', bottom=y_1) p3 = plt.bar(ind, y_3, width, color='g', bottom=y_3_bottom) self.autolabel(p1) self.autolabel(p2) self.autolabel(p3) plt.title(title + '\n') plt.xticks(ind+width/2., x_ray ) plt.yticks(np.arange(0,y_max,20)) plt.legend( (p1[0], p2[0], p3[0]), (legend1, legend2, legend3) ) plt.grid(True) plt.savefig(outputfile)
def plot_graph_distribution(distribution, filename = "filename", title = "title", xlabel = "xlabel", ylabel = "ylabel") : plotx = [] ploty = [] for k in distribution : y = distribution[k] if k == 0 or y == 0 : continue # plotx.append(math.log(k, 2)) # ploty.append(math.log(y, 2)) plotx.append(k) ploty.append(y) rects1 = plt.bar(index, means_men, bar_width, alpha=opacity, color='b', yerr=std_men, error_kw=error_config, label='Men') plt.bar(plotx,ploty, 'ro') plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.savefig(filename + '.png')
def draw_bar(data): alg1 = [] alg2 = [] alg3 = [] for item in data: if item['Alg3_Time'] != -1: alg1.append(item['Alg1_Time']) alg2.append(item['Alg2_Time']) alg3.append(item['Alg3_Time']) alg1 = np.array(alg1) alg2 = np.array(alg2) alg3 = np.array(alg3) add_index = range(len(k_index)) p1 = plt.bar(add_index, alg1, width, color='r',align="center",) p2 = plt.bar(add_index, alg2, width, color='y', bottom=alg1,align="center",) p3 = plt.bar(add_index, alg3, width, color='b', bottom=alg1+alg2,align="center",) plt.ylabel('running time (seconds)') plt.xlabel('k') plt.title('Breakdown of computation time on NetHEPT') #plt.xticks((0,1,2),(u'ÄÐ',u'Å®','as')) plt.xticks(add_index,k_index) plt.legend((p1[0],p2[0],p3[0]), ('alg1', 'alg2','alg3'),loc=2) plt.savefig('Breakdown_computation_time') plt.close()
def graph_startpos(startpos, gene_name): """ Make a histogram of normally distributed random numbers and plot the analytic PDF over it """ d = defaultdict(int) x = arange(-1, 4) print x for i in x: d[i] = 0 for pos in startpos: d[pos+1] += 1 fig = plt.figure() ax = fig.add_subplot(111) plt.bar(x, d.values()) print d.values() plt.xticks( x + 0.5 , (" ", 0, 1, 2, " ") ) ax.set_xlabel('Reading Frame') ax.set_ylabel('# Reads') fig.suptitle('Distribution of open reading frames', fontsize=14, fontweight='bold') if (gene_name != None): ax.set_title("Restricted to gene {0}".format(gene_name), fontsize=12) plt.show()
def test_bbox_inches_tight(): #: Test that a figure saved using bbox_inches='tight' is clipped right rcParams.update(rcParamsDefault) data = [[ 66386, 174296, 75131, 577908, 32015], [ 58230, 381139, 78045, 99308, 160454], [ 89135, 80552, 152558, 497981, 603535], [ 78415, 81858, 150656, 193263, 69638], [139361, 331509, 343164, 781380, 52269]] colLabels = rowLabels = [''] * 5 rows = len(data) ind = np.arange(len(colLabels)) + 0.3 # the x locations for the groups cellText = [] width = 0.4 # the width of the bars yoff = np.array([0.0] * len(colLabels)) # the bottom values for stacked bar chart fig, ax = plt.subplots(1, 1) for row in xrange(rows): plt.bar(ind, data[row], width, bottom=yoff) yoff = yoff + data[row] cellText.append(['']) plt.xticks([]) plt.legend([''] * 5, loc=(1.2, 0.2)) # Add a table at the bottom of the axes cellText.reverse() the_table = plt.table(cellText=cellText, rowLabels=rowLabels, colLabels=colLabels, loc='bottom')
def normDistribution(self, list, bins): abs = map(np.linalg.norm, list) hist, bins = np.histogram(abs, bins = bins) width = 0.7 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hist, align='center', width=width) plt.show()
#Exploratory Data Analysis data = data.split("\n") data_list = [] for i in data: data_list.append(i.split(",")) data_list = [i for item in data_list for i in item] item_frequencies = Counter(data_list) item_frequencies = sorted(item_frequencies.items(), key = lambda x:x[1]) frequencies = list(reversed([i[1] for i in item_frequencies])) items = list(reversed([i[0] for i in item_frequencies])) #plotting graph plt.bar(height = frequencies[0:11], x = list(range(0, 11)), color = 'rgbkymc') plt.xticks(list(range(0, 11), ), items[0:11]) plt.xlabel("items") plt.ylabel("Count") plt.show() data_series = pd.DataFrame(pd.Series(data_list)) data_series = data_series.iloc[:9835, :] # removing the last empty transaction data_series.columns = ["transactions"] X = data_series['transactions'].str.join(sep = '*').str.get_dummies(sep = '*') frequent_itemsets = apriori(X, min_support = 0.0075, max_len = 4, use_colnames = True) frequent_itemsets.sort_values('support', ascending = False, inplace = True) #plotting graph plt.bar(x = list(range(0, 11)), height = frequent_itemsets.support[0:11], color ='rgmyk')
intensity_NSCL = [1.78e4, 2.92e3, 4.01e2, 52.9, 6.22, .654, .0642, 8.11e-4] #32,33,34,35,36,37,38,40 intensity_FRIB = [2.27e6, 3.6e5, 4.44e4, 7.45e3, 9.32e2, 5.33e1, 9.75, .114] intensity_FRIB_online = [ 1.79e6, 2.97e5, 4.41e4, 6.05e3, 7.88e2, 9.85e1, 13.1, .232 ] # Set position of bar on X axis r1 = np.arange(len(intensity_NSCL)) r2 = [x + barWidth for x in r1] r3 = [x + barWidth for x in r2] # Make the plot plt.bar(r1, intensity_NSCL, color='#ff0000', width=barWidth, edgecolor='white', label='NSCL') plt.bar(r2, intensity_FRIB, color='#4B8BBE', width=barWidth, edgecolor='white', label='FRIB') plt.bar(r3, intensity_FRIB_online, color='#2d7f5e', width=barWidth, edgecolor='white', label='FRIB Online')
import numpy as np import matplotlib.pyplot as plt prj = [2, 5, 8, 12, 14] num_of_prj = 4 sol_list = [] power = [] # for i in range(1, num_of_prj): for i in prj: directory = "C:/thesisRepo/c_files/dwt_prj" + str( i ) + "/solution1/project1/project1.runs/impl_1/design_1_wrapper_power_routed.rpt" sol_list.append("sol" + str(i)) with open(directory) as myfile: power.append(myfile.readlines()[32].split()[6]) #print (myfile.readlines()[32].split()[6]) power = [float(i) for i in power] plt.bar(sol_list, power) for a, b in zip(sol_list, power): plt.text( a, b, str(b) + "__" + str(round((b - power[0]) / power[0] * 100, 2)) + "%") plt.show()
def barplot_neighbors( Nrange=2 ** np.arange(1, 11), Drange=2 ** np.arange(7), krange=2 ** np.arange(10), N=1000, D=64, k=5, leaf_size=30, dataset="digits", ): algorithms = ("kd_tree", "brute", "ball_tree") fiducial_values = {"N": N, "D": D, "k": k} # ------------------------------------------------------------ # varying N N_results_build = {alg: np.zeros(len(Nrange)) for alg in algorithms} N_results_query = {alg: np.zeros(len(Nrange)) for alg in algorithms} for i, NN in enumerate(Nrange): print("N = %i (%i out of %i)" % (NN, i + 1, len(Nrange))) X = get_data(NN, D, dataset) for algorithm in algorithms: nbrs = neighbors.NearestNeighbors( n_neighbors=min(NN, k), algorithm=algorithm, leaf_size=leaf_size ) t0 = time() nbrs.fit(X) t1 = time() nbrs.kneighbors(X) t2 = time() N_results_build[algorithm][i] = t1 - t0 N_results_query[algorithm][i] = t2 - t1 # ------------------------------------------------------------ # varying D D_results_build = {alg: np.zeros(len(Drange)) for alg in algorithms} D_results_query = {alg: np.zeros(len(Drange)) for alg in algorithms} for i, DD in enumerate(Drange): print("D = %i (%i out of %i)" % (DD, i + 1, len(Drange))) X = get_data(N, DD, dataset) for algorithm in algorithms: nbrs = neighbors.NearestNeighbors( n_neighbors=k, algorithm=algorithm, leaf_size=leaf_size ) t0 = time() nbrs.fit(X) t1 = time() nbrs.kneighbors(X) t2 = time() D_results_build[algorithm][i] = t1 - t0 D_results_query[algorithm][i] = t2 - t1 # ------------------------------------------------------------ # varying k k_results_build = {alg: np.zeros(len(krange)) for alg in algorithms} k_results_query = {alg: np.zeros(len(krange)) for alg in algorithms} X = get_data(N, DD, dataset) for i, kk in enumerate(krange): print("k = %i (%i out of %i)" % (kk, i + 1, len(krange))) for algorithm in algorithms: nbrs = neighbors.NearestNeighbors( n_neighbors=kk, algorithm=algorithm, leaf_size=leaf_size ) t0 = time() nbrs.fit(X) t1 = time() nbrs.kneighbors(X) t2 = time() k_results_build[algorithm][i] = t1 - t0 k_results_query[algorithm][i] = t2 - t1 plt.figure(figsize=(8, 11)) for sbplt, vals, quantity, build_time, query_time in [ (311, Nrange, "N", N_results_build, N_results_query), (312, Drange, "D", D_results_build, D_results_query), (313, krange, "k", k_results_build, k_results_query), ]: ax = plt.subplot(sbplt, yscale="log") plt.grid(True) tick_vals = [] tick_labels = [] bottom = 10 ** np.min( [min(np.floor(np.log10(build_time[alg]))) for alg in algorithms] ) for i, alg in enumerate(algorithms): xvals = 0.1 + i * (1 + len(vals)) + np.arange(len(vals)) width = 0.8 c_bar = plt.bar(xvals, build_time[alg] - bottom, width, bottom, color="r") q_bar = plt.bar(xvals, query_time[alg], width, build_time[alg], color="b") tick_vals += list(xvals + 0.5 * width) tick_labels += ["%i" % val for val in vals] plt.text( (i + 0.02) / len(algorithms), 0.98, alg, transform=ax.transAxes, ha="left", va="top", bbox=dict(facecolor="w", edgecolor="w", alpha=0.5), ) plt.ylabel("Time (s)") ax.xaxis.set_major_locator(ticker.FixedLocator(tick_vals)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(tick_labels)) for label in ax.get_xticklabels(): label.set_rotation(-90) label.set_fontsize(10) title_string = "Varying %s" % quantity descr_string = "" for s in "NDk": if s == quantity: pass else: descr_string += "%s = %i, " % (s, fiducial_values[s]) descr_string = descr_string[:-2] plt.text( 1.01, 0.5, title_string, transform=ax.transAxes, rotation=-90, ha="left", va="center", fontsize=20, ) plt.text( 0.99, 0.5, descr_string, transform=ax.transAxes, rotation=-90, ha="right", va="center", ) plt.gcf().suptitle("%s data set" % dataset.capitalize(), fontsize=16) plt.figlegend((c_bar, q_bar), ("construction", "N-point query"), "upper right")
print("For number of features = " + str(n[i])) print("Accuracy = ") print((ACC[0] + ACC[1] + ACC[2])/3) print("PPV = ") print((PPV[0] + PPV[1]+PPV[2])/3) print("NPV = ") print((NPV[0]+NPV[1]+NPV[2])/3) print("SENSITIVITY = ") print((sensitivity[0]+sensitivity[1]+sensitivity[2])/3) print("SPECIFICITY = ") print((specificity[0]+specificity[1]+specificity[2])/3) print("F-Score") print(f1_score(y_test, y_pred, average='micro')) print("-----------------------------------------------------------") print("-----------------------------------------------------------") print("-----------------------------------------------------------") acc.append((ACC[0] + ACC[1] + ACC[2])/3) fs.append(f1_score(y_test, y_pred, average='micro')) plt.subplots() plt.bar(n,acc,width = 50) plt.xlabel('Number of Features') plt.ylabel('Accuracy') plt.title('Accuracy vs Number of Features for NAIVEBAYES') plt.show() plt.subplots() plt.bar(n,fs,width = 50) plt.xlabel('F Score') plt.ylabel('Number of Features') plt.title('F score vs Number of Features for NAIVEBAYES') plt.show()
import matplotlib.pyplot as plt import numpy as np langs = ('Python', 'C', 'C++', 'Java', 'Perl', 'Scala', 'Lisp') y_pos = np.arange(len(langs)) tiobe_ratings = [9.09,16.45,6.21,15.1,.87,.31,.36] plt.title('TIOBE Index for July 2020') plt.bar(y_pos, tiobe_ratings, align='center', alpha=0.8) plt.xticks(y_pos, langs) plt.ylabel('TIOBE Rating (%)') plt.show()
import numpy as np import matplotlib import matplotlib.pyplot as plt import scipy.stats from scipy.stats import bernoulli, poisson, binom a = np.arange(2) # Bernoulli colors = matplotlib.rcParams['axes.color_cycle'] plt.figure(figsize=(12, 8)) for i, p in enumerate([0.1, 0.2, 0.6, 0.7]): ax = plt.subplot(1, 4, i + 1) plt.bar(a, bernoulli.pmf(a, p), label=p, color=colors[i], alpha=0.5) ax.xaxis.set_ticks(a) plt.legend(loc=0) if i == 0: plt.ylabel("PDF at $k$") plt.show() plt.suptitle("Bernoulli probability") # Poisson k = np.arange(20) colors = matplotlib.rcParams['axes.color_cycle'] plt.figure(figsize=(12, 8)) for i, lambda_ in enumerate([1, 4, 6, 12]): plt.bar(k, poisson.pmf(k, lambda_),
ddqn_choose_list = np.array([198, 413, 649, 871, 1072]) pred_choose_list = np.array([200, 414, 650, 870, 1070]) offline_choose_list = np.array([184, 384, 600, 810, 994]) err_fa_list = [8, 11, 19, 26, 31] err_fc_list = [2, 4, 6, 8, 10] err_dq_list = [2, 6, 10, 14, 16] err_pr_list = [2, 4, 6, 8, 10] x = range(len(label_list)) error_params = dict(elinewidth=2, ecolor='black', capsize=3) # 设置误差标记参数 fig, ax = plt.subplots() rects1 = plt.bar(x, height=fedavg_list, width=0.15, color='#2ca02c', label="FedAvg [Google Team]", hatch='.') # , yerr=err_fa_list, error_kw=error_params) rects11 = plt.bar(x, height=fedavg_choose_list - fedavg_list, width=0.15, color='#2ca02c', alpha=0.5, bottom=fedavg_list) rects2 = plt.bar([i + 0.15 for i in x], height=fedcs_list, color='#1f77b4', width=0.15, label="FedCS [Nishio, 2019]", hatch='xx') # , yerr=err_fc_list, error_kw=error_params) rects21 = plt.bar([i + 0.15 for i in x], height=fedcs_choose_list - fedcs_list, width=0.15, color='#1f77b4', alpha=0.5, bottom=fedcs_list) rects3 = plt.bar([i + 0.3 for i in x], height=ddqn_list, color='#ff7f0e', width=0.15, label="DDQN-based (Proposed)", hatch='') # , yerr=err_dq_list, error_kw=error_params) rects31 = plt.bar([i + 0.3 for i in x], height=pred_choose_list - ddqn_list, width=0.15, color='#ff7f0e', alpha=0.5, bottom=ddqn_list) rects4 = plt.bar([i + 0.45 for i in x], height=offline_list, color='#d62728', width=0.15, label="Offline", hatch='\\') # , yerr=err_pr_list, error_kw=error_params)
(-1,TIME_SAMPLES_PER_HOUR) ) trueStdCurrentAppliance = trueMeansCurrentAppliance.std(axis=1) trueMeansCurrentAppliance = trueMeansCurrentAppliance.mean(axis=1) trueInd = np.arange(0, 3 * len(trueMeansCurrentAppliance), 3) predMeansCurrentAppliance = \ predMeanByHouse[plotDayIndex,:,applianceNum] predMeansCurrentAppliance = np.reshape( predMeansCurrentAppliance, \ (-1,TIME_SAMPLES_PER_HOUR) ) predStdCurrentAppliance = predMeansCurrentAppliance.std(axis=1) predMeansCurrentAppliance = predMeansCurrentAppliance.mean(axis=1) predInd = np.arange(1, 3 * len(predMeansCurrentAppliance), 3) if applianceNum == 2: truePlot = plt.bar(trueInd, trueMeansCurrentAppliance, barWidth, \ yerr=trueStdCurrentAppliance, \ capsize=5,error_kw={'alpha':0.5}) predPlot = plt.bar(predInd, predMeansCurrentAppliance, barWidth, \ yerr=predStdCurrentAppliance, \ capsize=5,error_kw={'alpha':0.5}) else: truePlot = plt.bar(trueInd, trueMeansCurrentAppliance, barWidth, \ bottom=trueMeansPreviousAppliance, \ yerr=trueStdPreviousAppliance, \ capsize=5,error_kw={'alpha':0.5}) predPlot = plt.bar(predInd, predMeansCurrentAppliance, barWidth, \ bottom=predMeansPreviousAppliance, \ yerr=predStdPreviousAppliance, \ capsize=5,error_kw={'alpha':0.5})
import numpy as np import matplotlib.pyplot as plt filename = './befkbhalderstatkode.csv' bef_stats_df = np.genfromtxt( filename, delimiter=',', dtype=np.uint, skip_header=1) print(type(bef_stats_df), ' of size: ', bef_stats_df.size) print('The skip_header=1 means that we have only the data\n\nfirst line:\n', bef_stats_df[0], '\nlast line\n', bef_stats_df[len(bef_stats_df)-1]) dd = bef_stats_df mask = (dd[:, 0] == 1998) # for all rows filter column/index = 0 to be 1998 dd[mask] mask = (dd[:, 0] == 2015) & (dd[:, 2] == 18) & (dd[:, 3] == 5100) print(dd[mask]) plt.axis([0, 10, 300, 600]) plt.bar(dd[:, 1], dd[:, 4]) np.sum(dd[mask][:, 4]) plt.show()
fig, axs = plt.subplots(nrows=num_classes, ncols=cols, figsize=(5, 10)) fig.tight_layout() for i in range(cols): for j in range(num_classes): x_selected = X_train[y_train == j] axs[j][i].imshow( x_selected[random.randint(0, (len(x_selected) - 1)), :, :], cmap=plt.get_cmap('gray')) axs[j][i].axis("off") if i == 2: axs[j][i].set_title(str(j)) num_of_samples.append(len(x_selected)) print(num_of_samples) plt.figure(figsize=(12, 4)) plt.bar(range(0, num_classes), num_of_samples) plt.title("Distribution of the train dataset") plt.xlabel("Class number") plt.ylabel("Number of images") plt.show() X_train = X_train.reshape(60000, 28, 28, 1) X_test = X_test.reshape(10000, 28, 28, 1) y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10) X_train = X_train / 255 X_test = X_test / 255
def bar_plots(mydict, metric, path_figs, learning): import matplotlib.pyplot as plt import numpy as np import scipy.stats my_list = ['Control','No_VIPcells', 'No_VIPCR', 'No_VIPCCK', 'No_VIPPVM', 'No_VIPNVM', 'No_VIPCRtoOLM','No_VIPCRtoBC'] A = mydict A_means = [] A_sems = [] for case in my_list: A_means.append(np.mean(A[case])) A_sems.append(scipy.stats.sem(A[case])) plt.figure(1, dpi=300) y = A_means labels = my_list N = len(y) x = range(N) p1, p2, p3, p4, p5, p6, p7, p8 = plt.bar(x, y, yerr=A_sems) p1.set_facecolor('blue') p2.set_facecolor('red') p3.set_facecolor('green') p4.set_facecolor('yellow') p5.set_facecolor('lightblue') p6.set_facecolor('olive') p7.set_facecolor('darkmagenta') p8.set_facecolor('darkorange') plt.xticks(x, labels, rotation='45') plt.ylabel(metric, fontsize=16) plt.title(metric) plt.savefig(path_figs+'/'+learning+'_'+metric+'_barplot.pdf',format='pdf',dpi=300) plt.cla() plt.clf() plt.close() # Make Boxplots A_list = [] for case in my_list: A_list.append(list(mydict[case])) plt.figure(1, dpi=300) y = A_list labels = my_list N = len(y) x = range(1, N+1) # notch shape box plot bplot = plt.boxplot(y, notch=True, vert=True, patch_artist=True, labels=labels) # will be used to label x-ticks # fill with colors colors = ['blue', 'red', 'green', 'yellow', 'lightblue', 'olive', 'darkmagenta','darkorange' ] for patch, color in zip(bplot['boxes'], colors): patch.set_facecolor(color) for element in ['fliers', 'means', 'medians', 'caps']: plt.setp(bplot[element], color='black') plt.xticks(x, labels, rotation='45') plt.ylabel(metric, fontsize=16) plt.savefig(path_figs+'/'+learning+'_'+metric+'_boxplot.pdf',format='pdf',dpi=300) plt.cla() plt.clf() plt.close()
import numpy as np from PIL import Image from matplotlib import pyplot as plt im = Image.open('ciphertext_morning.png') mgb = np.array(im) r, g, b = mgb[:, :, 0], mgb[:, :, 1], mgb[:, :, 2] rku = Image.fromarray(r) gku = Image.fromarray(g) bku = Image.fromarray(b) rhis = rku.histogram() ghis = gku.histogram() bhis = bku.histogram() plt.style.use('ggplot') plt.subplot(3, 1, 1) plt.bar(range(256), rhis, edgecolor="none") plt.title("histogram R") plt.xlim(0, 255) plt.subplot(3, 1, 2) plt.bar(range(256), ghis, edgecolor="none") plt.title("histogram G") plt.xlim(0, 255) plt.subplot(3, 1, 3) plt.bar(range(256), bhis, edgecolor="none") plt.title("histogram B") plt.xlim(0, 255) plt.tight_layout() plt.savefig('histogram rgb.png') plt.show()
print('-----------------------------------------------') series_2 = {'x': list(), 'y': list()} _data_2 = client.query(data_deplay_query('round_trip_2')) for k, v in _data_2.items(): # print(k[1]['num_of_sensor']) # print(list(v)[0]['mean']) series_2['x'].append(int(k[1]['num_of_sensor'])) series_2['y'].append(float(list(v)[0]['mean'] + 1)) print(series_1) print(series_2) width = 1 # the width of the bars: can also be len(x) sequence p1 = plt.bar(series_1['x'], series_1['y'], width, color='#d62728') p2 = plt.bar(series_2['x'], series_2['y'], width, bottom=series_1['y']) plt.ylabel('Transmission Time (seconds)') plt.xlabel('Number of sensors per platform (on 5 platforms)') plt.title('Tranmission time by number of sensor') plt.xticks(series_1['x']) # plt.yticks(np.arange(0, 300, 10)) plt.legend((p1[0], p2[0]), ('Sensor - Platform Transmission Time', 'Platform - Cloud Transmission Time')) # def autolabel(rects): # """ # Attach a text label above each bar displaying its height # """ # for rect in rects:
ax.set_title('number of orders per month') ax.set_xlabel('month') ax.set_ylabel('orders') x = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] y = [january, february, march, april, may, june, july, august, september, october, november, december] ax.bar(x,y, color=plt.cm.plasma_r(y)) for a in range(0,12): num = str(y[a]) ax.text(x[a],y[a],num, va = 'center', ha = 'left', bbox = dict(facecolor="w", alpha=.5)) plt.show() #""" """ months = ('Aug', 'Sep', 'Dec', 'January', 'February') y_pos = np.arange(len(months)) numOrders = [august, september, december, january, february] plt.bar(y_pos,numOrders, align='center', alpha=.5) plt.xticks(y_pos,months) plt.ylabel('Number of orders') plt.title('Months vs orders') plt.show() """
cust_ID.describe() #################################################################### #Found out there was no much difference in the mean loan amount received by each individal based on the #home ownership criteria. other factors like credit card history played a big part in the loan amount received m = cust_ID.groupby([ 'Home_ownership', ])['Loan_Amount'].mean() m.head(20) y = m.tolist() x = m.keys().tolist() pos = np.arange(len(m)) plt.bar(pos, y, color='blue', edgecolor='black') plt.xticks(pos, x) plt.xlabel('Home_ownership', fontsize=16) plt.ylabel('Loan_Amount', fontsize=16) plt.title('Barchart - Amount_Received', fontsize=20) plt.show() #sorting and grouping data by loan purpose and loan amount. Wanted to find the correlation between those values y = cust_ID.sort_values(by='Loan_Purpose', na_position='first') #place any missing value first y = cust_ID.sort_index(axis=1) y = cust_ID.sort_index(axis=1, ascending=False) y.head(10) x = cust_ID.sort_values(['Loan_Purpose']) #place any missing value first x.head(10)
import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("covid/covid_19_data.csv") # türkiye=df[df["Country/Region"]=="Turkey"] # plt.bar(türkiye.Deaths,türkiye.Recovered) # plt.show() # sayı=np.array([1,2,3,4,5,6,7,8,9]) # karesi=sayı**2 # plt.bar(sayı,karesi) # plt.xlabel("sayı değeri") # plt.ylabel("sayının karesi") # plt.title("sayıların karesini alma") # plt.show() ülke = [ "Türkiye", "Abd", "Almanya", "İtalya", "İspanya", "Fransa", "Güney Kore", "Japonya", "UK", "Çin", "Hindistan" ] oran = [40, 34.7, 29.2, 12.5, 11.6, 10.6, 9.7, 7.3, 6.6, 3.6, 2.3] plt.xlabel("Ülkeler") plt.ylabel("Oranlar") plt.title("yoğun bakım yatak sayısı") plt.bar(ülke, oran) plt.show()
def generate_graphs(datafile): with open(datafile, 'r') as f: wholefile = f.read() wholefile = json.loads(wholefile) # set up folder for pngs try: os.chdir(IMAGEDIR) except: os.mkdir(IMAGEDIR) os.chdir(IMAGEDIR) for graph in wholefile: logging.debug("Graphing %s." % graph['uniquename']) if graph['type'] == 'bar' and graph['data']: d = graph['data'] # cast the keys from strings to ints d = {int(k): d[k] for k in d.keys()} # store dict's values in array for graphing barheights = [] for i in range(1, max(d.keys()) + 1): barheights.append(d.get(i, 0)) barheights = barheights[:BINS] bottom = 0 barwidth = 1 xlocations = np.arange(len(barheights)) fig = plt.figure() plt.bar( xlocations, barheights, barwidth, bottom, color=(.4, .4, .4), linewidth=0, ) # graph labels plt.suptitle(graph.get('name', ''), fontsize=14) plt.title(graph.get('additional', ''), fontsize=10) plt.xlabel(graph['xlabel']) plt.ylabel(graph['ylabel']) # remove right&top axes&ticks ax = fig.gca() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.tick_params(top=False, right=False) ax.set_xticks(np.arange(BINS) + barwidth / 2.) ax.set_xticklabels(d.keys()[:BINS]) # this may be a more robust solution: # http://matplotlib.org/faq/howto_faq.html#automatically-make-room-for-tick-labels fig.set_size_inches(6, 4.5) filename = graph['uniquename'] + '.png' plt.savefig(filename, dpi=80) logging.info("Created file %s" % filename) plt.clf() elif graph['type'] == 'timeseries' and graph['data']: d = graph['data'] fig = plt.figure() x = [ datetime.strptime(key, "%Y-%m-%d") for key in sorted(d.keys()) ] y = [d[key] for key in sorted(d.keys())] plt.plot(x, y, 'o-') fig.autofmt_xdate() # labels plt.suptitle(graph.get('name', ''), fontsize=14) plt.title(graph.get('additional', ''), fontsize=10) plt.ylabel(graph['ylabel']) # save and resize image file fig.set_size_inches(6, 4.5) filename = graph['uniquename'] + '.png' plt.savefig(filename, dpi=80) logging.info("Created file %s" % filename) plt.clf() else: message = 'Did NOT create graph for "%s" (type: %s) ' % ( graph['uniquename'], graph['type']) if not graph['data']: message += 'because it didn\'t contain any data' else: message += 'because it\'s not a supported graph type' logging.error(message)
import pandas as pd import matplotlib.pyplot as plt data = [[2,20],[4,22],[6,26],[8,28],[10,29],[12,29],[14,29],[16,31],[18,30],[20,25],[22,24],[24,22]] df=pd.DataFrame(data,columns = ['time','temperature']) plt.plot(df['time'], df['temperature']) plt.bar(df['time'], df['temperature']) plt.ylabel('time') plt.xlabel('temperature') plt.title('monday') plt.show() data1 = [[2,20],[4,22],[6,26],[8,28],[10,29],[12,29],[14,29],[16,31],[18,30],[20,25],[22,24],[24,22]] df=pd.DataFrame(data1,columns = ['time','temperature']) plt.plot(df['time'], df['temperature']) plt.bar(df['time'], df['temperature']) plt.ylabel('time') plt.xlabel('temperature') plt.title('tuesday') plt.show() data = [[2,20],[4,22],[6,26],[8,28],[10,29],[12,29],[14,29],[16,31],[18,30],[20,25],[22,24],[24,22]] df=pd.DataFrame(data,columns = ['time','temperature']) plt.plot(df['time'], df['temperature']) plt.bar(df['time'], df['temperature']) plt.ylabel('time') plt.xlabel('temperature') plt.title('wednesday') plt.show() data = [[2,20],[4,22],[6,26],[8,28],[10,29],[12,29],[14,29],[16,31],[18,30],[20,25],[22,24],[24,22]] df=pd.DataFrame(data,columns = ['time','temperature']) plt.plot(df['time'], df['temperature']) plt.bar(df['time'], df['temperature']) plt.ylabel('time')
@author: oyeda """ import pandas as pd import matplotlib.pyplot as plt dataframe = pd.read_csv('C:/Users/oyeda/Desktop/AUTOGIS/ass7/Kumpula-June-2016-w-metadata.txt', skiprows= 8) dataframe.columns x = dataframe['YEARMODA'] y = dataframe['TEMP'] plt.plot(x,y) #'r is the colour, o is the circle point, -- is the line connecting the points plt.plot(x,y, 'ro--') plt.title('Kumpula Temperature in June 2016') plt.xlabel('Date') plt.ylabel('Temperatue [F]') plt.text(20160604, 68, 'High temp in early june') plt.axis([20160615, 20160630, 55.0, 70.0]) plt.bar(x,y) plt.axis([20160615, 20160630, 55.0, 70.0])
def optimalK(data, nrefs=3, maxClusters=15, randomSeed=51, plotting=False, figPath=None): """ Calculates KMeans optimal K using Gap Statistic from Tibshirani, Walther, Hastie Params: data: ndarry of shape (n_samples, n_features) nrefs: number of sample reference datasets to create maxClusters: Maximum number of clusters to test for randomSeed: seed to random number generator plotting: True to plot the gap statistic results figPath: Only considered if plotting is True. If None, figure is displayed in console instead Returns: optimalK """ gaps = np.zeros((len(range(1, maxClusters)),)) resultsdf = pd.DataFrame({'clusterCount':[], 'gap':[]}) for gap_index, k in enumerate(range(1, maxClusters)): # Holder for reference dispersion results refDisps = np.zeros(nrefs) # For n references, generate random sample and perform kmeans getting resulting dispersion of each loop for i in range(nrefs): # Create new random reference set randomReference = np.random.random_sample(size=data.shape) # Fit to it np.random.seed(randomSeed) km = KMeans(k) km.fit(randomReference) refDisp = km.inertia_ refDisps[i] = refDisp # Fit cluster to original data and create dispersion np.random.seed(randomSeed) km = KMeans(k) km.fit(data) origDisp = km.inertia_ # Calculate gap statistic gap = np.log(np.mean(refDisps)) - np.log(origDisp) # Assign this loop's gap statistic to gaps gaps[gap_index] = gap resultsdf = resultsdf.append({'clusterCount':k, 'gap':gap}, ignore_index=True) k = gaps.argmax() + 1 # Plus 1 because index of 0 means 1 cluster is optimal, index 2 = 3 clusters are optimal gapdf = resultsdf if plotting: plt.rc('font', size=15) # controls default text sizes plt.rc('axes', titlesize=17) # fontsize of the axes title plt.rc('axes', labelsize=17) # fontsize of the x and y labels plt.rc('xtick', labelsize=15) # fontsize of the tick labels plt.rc('ytick', labelsize=15) # fontsize of the tick labels plt.rc('legend', fontsize=15) # legend fontsize plt.rc('figure', titlesize=17) # fontsize of the figure title colorBar = ['blue' for i in range(len(gapdf.clusterCount))] colorBar[int(gapdf[gapdf.clusterCount == k].clusterCount.values[0]-1)] = 'red' plt.figure(figsize=(10, 6)) #plt.plot(gapdf.clusterCount, gapdf.gap, linewidth=3) #plt.scatter(gapdf[gapdf.clusterCount == k].clusterCount, gapdf[gapdf.clusterCount == k].gap, s=250, c='r') plt.bar(gapdf.clusterCount, gapdf.gap, align='center', alpha=0.6, color=colorBar) #plt.grid(True) low = min(gapdf.gap.values) high = max(gapdf.gap.values) plt.ylim([max(0,low-0.8*(high-low)), min(high+0.4*high, high+0.4*(high-low))]) plt.xlabel('Number of Clusters') plt.ylabel('Gap Value') if figPath is not None: plt.savefig(figPath, bbox_inches = 'tight', pad_inches = 0.05) plt.close() return k
plt.xlabel('x->') plt.ylabel('y->') plt.title('graph') plt.xlim(0,20) plt.ylim(0,20) plt.plot(x,y,'--r',label='Sine Curve') plt.plot(x,z,':b',label='Graph 2') plt.legend(loc='upper center') plt.show() ''' ''' plt.scatter(x,y,s=100,c='red',marker='x') plt.show() ''' ''' plt.bar(x,y, color="green") plt.show() ''' ''' label=['Delhi','Mumbai','Calcutta', 'Chennai'] slices=[10,20,30,40] plt.pie(slices,labels=label,explode=(0,0,0.1,0)) plt.legend() plt.show() fig=plt.figure() plt1=fig.add_subplot(111,projection='3d') plt1.scatter(x,y,z,s=100,c='r') plt.show()
# importing package import matplotlib.pyplot as plt import numpy as np # create data x = ['A', 'B', 'C', 'D'] y1 = np.array([10, 20, 10, 30]) y2 = np.array([20, 25, 15, 25]) y3 = np.array([12, 15, 19, 6]) y4 = np.array([10, 29, 13, 19]) # plot bars in stack manner plt.bar(x, y1, color='r') plt.bar(x, y2, bottom=y1, color='b') plt.bar(x, y3, bottom=y1 + y2, color='y') plt.bar(x, y4, bottom=y1 + y2 + y3, color='g') plt.xlabel("Teams") plt.ylabel("Score") plt.legend(["Round 1", "Round 2", "Round 3", "Round 4"]) plt.title("Scores by Teams in 4 Rounds") plt.show()
def plot_feature_importances( feature_list , labels ): feature_list = np.array(feature_list) plt.bar(labels, feature_list) plt.show()
hit_y = list() miss_x = list() miss_y = list() for i in range(n): x = random.uniform(x1, x2) y = random.uniform(y1, y2) if math.sqrt((X - x)**2 + (Y - y)**2) <= radius: # changes hit += 1 hit_x.append(x) hit_y.append(y) else: miss_x.append(x) miss_y.append(y) PI = (((abs(x1 - x2) * abs(y1 - y2)) / radius**2) * (hit / n)) PI_list.append(PI) area = PI * radius**2 circle_area_list.append(area) print(f"{n:<18}{PI:<22.3f}{area:.3f}") plt.scatter(hit_x, hit_y, color='red', label="Hits") plt.scatter(miss_x, miss_y, color="green", label="Misses") plt.legend(loc="upper right") plt.show() trials = [str(item) for item in trials] plt.bar(trials, PI_list, color="red") plt.show() plt.bar(trials, circle_area_list, color="red") plt.show()
e1 = Link3D11((n0, n2), E, A2) e2 = Link3D11((n0, n3), E, A1) s = System() s.add_nodes(n0, n1, n2, n3) s.add_elements(e0, e1, e2) s.add_node_force(0, Fx=12) s.add_fixed_sup(1, 2, 3) s.solve() from matplotlib.ticker import FuncFormatter import matplotlib.pyplot as plt import numpy as np def stresses(x, pos): return "$%1.1fMPa$" % (x * 1e-3) x = np.arange(3) stress = [abs(el.sx[0][0]) for el in [e0, e1, e2]] formatter = FuncFormatter(stresses) fig, ax = plt.subplots() ax.yaxis.set_major_formatter(formatter) plt.bar(x, stress, 0.2, color=["r", "b", "g"]) ax.set_xticks(x + 0.1) ax.set_xticklabels(("$Bar 0$", "$Bar 1$", "$Bar 2$")) ax.set_ylabel("$N/kN$") ax.set_xlim([-0.5, 3]) plt.show()
# calculate theoretical CDFs % kappaCDF = curvatureCDF(kappaEdges, mu, gamma2) kappaNormCDF = curvatureCDF(2*kappaNormEdges / ( 1 - np.abs(kappaNormEdges)), mu, gamma2) kappaNormCDF[0] = 0 kappaNormCDF[-1] = 1 # fix normalization due to having no overflow bin for non-normalized curvature % kappaCDF = kappaCDF - kappaCDF[0] kappaCDF = kappaCDF / kappaCDF[-1] ## ---- plot comparison! ---- plt.figure(figsize=(16, 5)) plt.subplot(1, 2, 1) plt.bar(kappaBins, kappaDist, width = 1.5, facecolor='yellowgreen') plt.plot(kappaBins, np.diff(kappaCDF), 'blue', linewidth=2.5) plt.xlabel(r'Contour Curvature $\kappa$', fontsize=14) plt.ylabel(r'Probability Density $P(\kappa)$', fontsize=14) plt.title('Contour Curvature Distribution', fontsize=16) plt.legend(['Theory', 'Numerics'], fontsize=14) plt.subplot(1, 2, 2) plt.bar(kappaNormBins, kappaNormDist, width = 0.03, facecolor='yellowgreen') plt.plot(kappaNormBins, np.diff(kappaNormCDF), 'blue', linewidth=2.5) plt.xlabel(r'Normalized Contour Curvature $\hat{\kappa}$', fontsize=14) plt.ylabel(r'Probability Density $P(\hat{\kappa})$', fontsize=14) plt.title('Normalized Contour Curvature Distribution', fontsize=16) plt.legend(['Theory', 'Numerics'], fontsize=14) ## ---- Effect of Gaussian Filtering on NCC Distribution ---- ##
Ntime = len(time) j = 1 STOP = 0 while STOP == 0: try: dist = np.genfromtxt(filename,skip_header=24,usecols=[j],unpack=True) idx = np.where(dist<Threshold) Ncontacts = len(dist[idx]) if i == 0: contacts.append(Ncontacts) else: contacts[j-1] = Ncontacts + contacts[j-1] #print('res %d: %d/%d contacts' % (j,Ncontacts,len(dist))) j += 1 #print(j) except: #print('no more residues') STOP = 1 #print(j) Nres = j-1 res = np.linspace(1,Nres,Nres) total = Nres * Ntime #print(res) #print(contacts) plt.bar(res,np.asarray(contacts)/total,color='black') plt.xlabel(r'residue') plt.ylabel(r'PIP$_2$ contact frequency') plt.show()
t_levels = 5 hilbert_dims = hilbert_dimensions(c_levels, t_levels) m_ops = [] snapshots = 100 trajectories = 1000 endtime = 20000 sim_options = simulation_options(endtime, snapshots, m_ops, trajectories) initial_state = tensor(basis(hilbert_dims.c_levels, 0), basis(hilbert_dims.t_levels, 0)) results = solution(sys_params, hilbert_dims, initial_state, sim_options) cavity_zero_vector = Qobj(np.zeros(c_levels)) cavity_zero_matrix = cavity_zero_vector * cavity_zero_vector.dag() transmon_zero_vector = Qobj(np.zeros(t_levels)) transmon_zero_matrix = transmon_zero_vector * transmon_zero_vector.dag() rho_ss = tensor(cavity_zero_matrix, transmon_zero_matrix) for i in range(trajectories): state = results.states[i, snapshots - 1] rho_state = state * state.dag() trace_rho_state = rho_state.tr() trace_rho_before = rho_ss.tr() rho_ss = rho_ss + rho_state trace_rho_after = rho_ss.tr() trace_rho_difference = trace_rho_after - trace_rho_before print i rho_ss = rho_ss / trajectories trace = rho_ss.tr() rho_c = rho_ss.ptrace(0) indices = np.arange(c_levels) qsave(rho_ss, 'rho_ss_monte') plt.bar(indices, rho_c.diag()) plt.show()
experiment_repeats = int(1e+6) deck = build_deck() np.random.shuffle(deck) freq = np.array([0 for i in range(len(deck))]) foot_prints = np.array([0 for i in range(len(deck))]) for _ in range(experiment_repeats): start_number = np.random.randint(0, 10) result = start_number cum_sum = start_number while cum_sum < len(deck): foot_prints[cum_sum] += 1 result = deck[cum_sum] cum_sum += result freq[cum_sum - result] += 1 print("Result probabilities:") print({ index: freq[index] / experiment_repeats for index in range(len(deck)) if freq[index] > 0 }) plt.bar(range(len(deck)), foot_prints / sum(foot_prints)) plt.title("Density of footprints") plt.show()