def pie(df): classes = (df['class'].value_counts() / float(len(df)) * 100) classes.sort(ascending=False) classes = classes[classes > 1] pl.pie(list(classes) + [100 - classes.sum()], labels=list(classes.index) + ['OTHER']) pl.show()
def render(self): self.generateSpace() self.axes = list() for i, rectangle in enumerate(self.rectangles): ax = plt.axes(rectangle) keys = list(self.names_to_fractions[i].keys()) keys.sort() labels = keys fractions = list() for key in keys: fractions.append(self.names_to_fractions[i][key] * 100) explode = tuple(0.05 for i in range(len(fractions))) plt.pie(fractions, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) self.axes.append(ax) plt.show()
def plotSumPie(all_result_outputs, label=''): mapping = { 'Large D, No MH': 'D>=4,\nno MH', 'Large D, MH': 'D>=4,\nMH', 'Small D, No MH': 'D<4, no MH', 'Small D, MH': 'D<4, MH' } merged_data = mergeSamples(all_result_outputs, ['Total reads'] + ALL_LABELS, data_label='perOligoCounts') for col in ALL_LABELS: merged_data[col + ' Perc'] = merged_data[ col + ' Sum'] * 100.0 / merged_data['Total reads Sum'] merged_data.to_csv('data_dump_indel_pie.txt', sep='\t', columns=['Oligo Id'] + [col + ' Perc' for col in ALL_LABELS]) pie_vals = [merged_data[col + ' Perc'].mean() for col in ALL_LABELS] PL.figure(figsize=(4, 4)) wedge_labels = [mapping[x] if x in mapping else x for x in ALL_LABELS] PL.pie(pie_vals, labels=wedge_labels, autopct='%.1f', labeldistance=1.05, startangle=90.0, counterclock=False, colors=COLORS) PL.title('Average distribution\n of mutations\n per gRNA') PL.show(block=False) saveFig('pie_chart_cats')
def make_analysis_pie(sentences, title="Pie Chart", token=False, ignore_unknowns=False, show=True): ''' Analyzes the given text and generates a pie chart to show the proportions of etymological origins in it. :sentences: tagged sentences from the Brown corpus :title: title to go on the chart :token: whether to count token frequencies instead of word frequencies :ignore_unknowns: whether to have a slice for unknowns in the chart :show: whether to show the chart after completeion. :return: the proportions of each language origin in the text in the order 'Unknown', 'Other', 'Norse', 'Greek', 'Latin', 'French', 'Old English' ''' e = f = n = g = l = o = u = 0 if token: already_seen = [] unknowns = [] for sentence in sentences: for word, tag in sentence: if token: if word in already_seen: continue else: already_seen.append(word) label = label_word(word, tag) if label == "Unknown": label = label_word(word.lower(), tag) if label == "English": e += 1 elif label == "French": f += 1 elif label == "Norse": n += 1 elif label == "Latin": l += 1 elif label == "Greek": g += 1 elif label == "Other": o += 1 elif label == "Unknown": unknowns.append((word, tag)) u += 1 total = u + e + f + n + l + g + o fracs = [u/total, o/total, n/total, g/total, l/total, f/total, e/total] labels = 'Unknown', 'Other', 'Norse', 'Greek', 'Latin', 'French', 'Old English' colors = 'r', 'orange', 'b', 'c', 'm', 'y', 'g' if ignore_unknowns: total = e + f + n + l + g + o fracs = [o/total, n/total, g/total, l/total, f/total, e/total] labels = 'Other', 'Norse', 'Greek', 'Latin', 'French', 'English' colors = 'orange', 'b', 'c', 'm', 'y', 'g' pl.figure(figsize=(6, 6)) pl.axes([0.1, 0.1, 0.8, 0.8]) pl.pie(fracs, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90) pl.title(title) if show: pl.show() return fracs
def makePie(values): # make a square figure and axes pylab.figure(1, figsize=(6, 6)) # Initialise the data lists. labels = [] fracs = [] explode = [] # Check who mined the most most = max(values.iterkeys(), key=(lambda key: values[key])) # values should be in a dictionary format with the pilot names as keys. for pilot in values: labels.append(pilot) fracs.append(values[pilot]) if pilot == most: explode.append(0.05) else: explode.append(0) pylab.pie(fracs, explode=explode, labels=labels, autopct="%1.1f%%", shadow=True) pylab.savefig("images/ore.png", bbox_inches="tight") pylab.close()
def create_pie_chart(self, snapshot: 'Snapshot', filename: str = '') -> str: """ Create a pie chart that depicts the distribution of the allocated memory for a given `snapshot`. The chart is saved to `filename`. """ try: from pylab import figure, title, pie, axes, savefig from pylab import sum as pylab_sum except ImportError: return self.nopylab_msg % ("pie_chart") # Don't bother illustrating a pie without pieces. if not snapshot.tracked_total or snapshot.classes is None: return '' classlist = [] sizelist = [] for k, v in list(snapshot.classes.items()): if v['pct'] > 3.0: classlist.append(k) sizelist.append(v['sum']) sizelist.insert(0, snapshot.asizeof_total - pylab_sum(sizelist)) classlist.insert(0, 'Other') title("Snapshot (%s) Memory Distribution" % (snapshot.desc)) figure(figsize=(8, 8)) axes([0.1, 0.1, 0.8, 0.8]) pie(sizelist, labels=classlist) savefig(filename, dpi=50) return self.chart_tag % (self.relative_path(filename))
def breakdownpie(projdict): pylab.figure(1, figsize=(6,6)) ax = pylab.axes([0.1, 0.1, 0.8, 0.8]) noaotime, chiletime, yaletime, lsutime = 0,0,0,0 sunytime, gsutime, osutime, allotherstime = 0,0,0,0 for key in projdict: if key.split('-')[0]=='NOAO': noaotime+=projdict[key]['time'] elif key.split('-')[0]=='CHILE': chiletime+=projdict[key]['time'] elif key.split('-')[0]=='YALE': yaletime+=projdict[key]['time'] elif key.split('-')[0]=='LSU': lsutime+=projdict[key]['time'] elif key.split('-')[0]=='SUNY': sunytime+=projdict[key]['time'] elif key.split('-')[0]=='GSU': gsutime+=projdict[key]['time'] elif key.split('-')[0]=='OSU': osutime+=projdict[key]['time'] elif key.split('-')[0]!='STANDARD' and key.split('-')[0]!='STANDARDFIELD' and key.split('-')[0]!='ALL': allotherstime+=projdict[key]['time'] times={"NOAO":noaotime, "CHILE":chiletime, "YALE":yaletime, "LSU":lsutime, "SUNY":sunytime, "GSU":gsutime, "OSU":osutime, "OTHERS":allotherstime} labels=[key for key in times if times[key] > 0] values=[times[key] for key in times if times[key] > 0] explode=[.05 for i in values] pylab.pie(values,labels=labels, autopct='%1.1f%%', explode=explode, startangle=90, pctdistance=1.15, labeldistance= 1.3) pylab.savefig('breakdown.png') plt.close() return
def breakdownpie(projdict,datestart): pylab.figure(1, figsize=(6,6)) ax = pylab.axes([0.1, 0.1, 0.8, 0.8]) noaotime, chiletime, yaletime, lsutime = 0,0,0,0 sunytime, gsutime, osutime, allotherstime = 0,0,0,0 for key in projdict: if key.split('-')[0]=='NOAO': noaotime+=projdict[key]['time'] elif key.split('-')[0]=='CHILE': chiletime+=projdict[key]['time'] elif key.split('-')[0]=='YALE': yaletime+=projdict[key]['time'] elif key.split('-')[0]=='LSU': lsutime+=projdict[key]['time'] elif key.split('-')[0]=='SUNY': sunytime+=projdict[key]['time'] elif key.split('-')[0]=='GSU': gsutime+=projdict[key]['time'] elif key.split('-')[0]=='OSU': osutime+=projdict[key]['time'] elif key.split('-')[0]!='STANDARD' and key.split('-')[0]!='STANDARDFIELD' and key.split('-')[0]!='ALL': allotherstime+=projdict[key]['time'] times={"NOAO":noaotime, "CHILE":chiletime, "YALE":yaletime, "LSU":lsutime, "SUNY":sunytime, "GSU":gsutime, "OSU":osutime, "OTHERS":allotherstime} labels=[key for key in times if times[key] > 0] values=[times[key] for key in times if times[key] > 0] explode=[.05 for i in values] pylab.pie(values,labels=labels, autopct='%1.1f%%', explode=explode, startangle=90, pctdistance=1.15, labeldistance= 1.3) pylab.savefig('images/'+datestart+'breakdown.png') plt.close() return
def pieChartCreation(graph_size, fracs, name1, name2, colors): """ Creates the big pie chart of the report. In this pie chart one fraction represents the amount of space sampled together by both trajectories, and the other two fractions represent the amount of space that was sampled by either A or B. @param graph_size: The graph size in pixels (?) @param fracs: a list or tuple containing the total number of elements of pure A, pure B, and mixed clusters. @param name1: String identifying the first trajectory. @param name2: String identifying the second trajectory. @param colors: dictionary with color descriptions for "A", "B" and "M" (Mixed) written in string format (for example "#FFFFFF" for white) @return : A PIL image of the pie chart. """ all_labels = ["A","B","Mixed"] all_colors = [colors['A'], colors['B'],colors['M']] this_labels = [] this_fracs = [] this_colors = [] mydpi = 100 fig = pylab.figure(figsize=(int(graph_size[0]/mydpi),int(graph_size[1]/mydpi)),dpi = mydpi) fig.set_facecolor('white') for i in range(len(fracs)): if fracs[i]!=0: this_labels.append(all_labels[i]) this_fracs.append(fracs[i]) this_colors.append(all_colors[i]) pylab.pie(this_fracs, labels=this_labels, autopct='%1.1f%%', shadow=False,colors=this_colors) pylab.title(shorten_name(name1)+" vs "+shorten_name(name2)) return fig2img(fig)
def main(): fig = pylab.figure(1, figsize=(6, 6)) pylab.pie([s[1] for s in MARKET_SHARE], labels=[s[0] for s in MARKET_SHARE], autopct='%1.1f%%') fig.savefig('images/market-share.png') pylab.clf()
def do_pie(prefix, dict, accesses): pylab.figure(1, figsize=(8,8)) ax = pylab.axes([0.1, 0.1, 0.8, 0.8]) labels = [] fracs = [] rest = 0 for item in dict.keys(): frac = dict[item] if (float(frac)/float(accesses) > 0.01): labels.append(item) fracs.append(frac) else: rest += frac i = 0 changed = False for x in labels: if x == 'undef': fracs[i] += rest labels[i] = 'other' changed = True i += 1 if changed == False: labels.append('other') fracs.append(rest) pylab.pie(fracs, labels=labels, autopct='%1.1f%%', pctdistance=0.75, shadow=True) pylab.savefig('%s%s-%d-%02d-%02d.png' % (dest, prefix, y1, m1, d1)) pylab.close(1)
def plot(self): """Histogram of the tissues found .. plot:: :include-source: :width: 80% from gdsctools import GenomicFeatures gf = GenomicFeatures() # use the default file gf.plot() """ if self.colnames.tissue not in self.df.columns: return data = pd.get_dummies(self.df[self.colnames.tissue]).sum() data.index = [x.replace("_", " ") for x in data.index] # deprecated but works for python 3.3 try: data.sort_values(ascending=False) except: data.sort(ascending=False) pylab.figure(1) pylab.clf() labels = list(data.index) pylab.pie(data, labels=labels) pylab.figure(2) data.plot(kind='barh') pylab.grid() pylab.xlabel('Occurences') # keep the try to prevent MacOS issue try:pylab.tight_layout() except:pass return data
def plot(data, total, grand_total): events = [(e, data[e][0]) for e in data] events.sort(key=lambda x: x[1]) def better_name(n): if n in list(better_names.keys()): return better_names[n] else: return n names = [e[0] for e in events] times = [e[1] for e in events] times_percent = [100.0 * t / float(total) for t in times] if grand_total is not None: comments = ["(%3.1f s, %3.1f%%)" % (time, 100.0 * time / grand_total) for time in times] else: comments = ["(%3.1f s)" % time for time in times] labels = [better_name(name) + " " + comment for name, comment in zip(names, comments)] explode = [0.05]*len(times) plt.pie(times_percent, autopct="%3.1f%%", labels=labels, colors=colors, startangle=0.0, explode=explode) plt.margins(x=0.2, y=0.1) plt.axis('equal')
def pieplot(tsv,show=False,distortion=3,wraplabel=10): '''pieplots atsv file with a header''' f = open(tsv,'r') exon = f.read() f.close() lines = exon.splitlines() head,data = lines[:2], lines[2:] head ='\n'.join(head) vals , labels, colors = [],[],[] for line in data: label,val = line.split('\t')[:2] val = float(val) if val > 0: c = color(label) colors.append(c) labels.append(wrap(label.replace('_',' ')+' '+str(round(val,2)),wraplabel)) vals.append(val**distortion) pylab.close('all') #pylab.figure(figsize=(13,13)) ax = pylab.axes(aspect=1) #f, ax = pylab.subplots(figsize(10,10)) pylab.pie(vals, labels=labels,colors=colors,) ax.set_title(head) fname = tsv[:-4]+'_pie.png' pylab.savefig(fname) if show:pylab.show()
def explode(self, figure_name, data=[], explode=[], labels=(), title='a graph'): """ Use this function to visualize data as a explode Params: data: The data will be visualized. explode: The distance between each bucket of the data. explode should be len(data) sequence or None. labels: The labels shows next to the bucket of the data. title: The title of the graph. Returns: save_name: str The file location of the result picture """ try: os.mkdir(self.save_path + '/explode') except: logging.warning('update explode in '+self.save_path) #Make the graph square. pylab.figure(1, figsize=(6,6)) ax = pylab.axes([0.1, 0.1, 0.8, 0.8]) pylab.title(title) pylab.pie(data, explode = explode, labels = labels, autopct = '%1.1f%%', startangle = 0) save_name = self.save_path + '/explode/' + figure_name pylab.savefig(save_name) pylab.clf() return self.request_path + '/explode/' + figure_name + '.png'
def showResults(request): Y_tally = 0 N_tally = 0 results_list = Choice.objects.all() for object in results_list: if object.votes == '1': Y_tally = Y_tally + 1 else: N_tally = N_tally + 1 # make a square figure and axes f = figure(figsize=(6,6)) ax = axes([0.1, 0.1, 0.8, 0.8]) #labels = 'Yes', 'No' labels = 'Yes', 'No' fracs = [Y_tally,N_tally] explode=(0, 0) pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True) title('Election Results', bbox={'facecolor':'0.8', 'pad':5}) canvas = FigureCanvasAgg(f) response = HttpResponse(content_type='image/png') canvas.print_png(response) matplotlib.pyplot.close(f) f.clear() return response
def pie(self): pylab.clf() keys = self.counter.keys() labels = dict([(k, float(self.counter[k]) / len(self)) for k in keys]) pylab.pie([self.counter[k] for k in keys], labels=[k + ':' + str(labels[k]) for k in keys])
def pie(self): pylab.clf() keys = self.counter.keys() labels = dict([(k,float(self.counter[k])/len(self)) for k in keys]) pylab.pie([self.counter[k] for k in keys], labels=[k + ':'+str(labels[k]) for k in keys])
def plot_water_usage(some_list, plt_title): ''' Creates a list "y" containing the water usage in Mgal/d of all counties. Y should have a length of 5. The list "y" is used to create a pie chart displaying the water distribution of the five groups. This function is provided by the project. ''' # accumulate public, domestic, industrial, irrigation, and livestock data y = [0, 0, 0, 0, 0] for item in some_list: y[0] += item[5] y[1] += item[6] y[2] += item[7] y[3] += item[8] y[4] += item[9] total = sum(y) y = [round(x / total * 100, 2) for x in y] # computes the percentages. color_list = ['b', 'g', 'r', 'c', 'm'] pylab.title(plt_title) pylab.pie(y, labels=USERS, colors=color_list) pylab.show() pylab.savefig("plot.png") # uncomment to save plot to a file
def analysis(): feature_importances_array = np.load("Default_AlexNet.npy") mean_feature_importances = np.mean(feature_importances_array, axis=0) for feature_importance, metric in zip(mean_feature_importances, METRIC_LIST): print("{}\t{}".format(metric, feature_importance)) time_indexes = np.arange(1, feature_importances_array.shape[0] + 1) feature_importances_cumsum = np.cumsum(feature_importances_array, axis=0) feature_importances_mean = feature_importances_cumsum for column_index in range(feature_importances_mean.shape[1]): feature_importances_mean[:, column_index] = feature_importances_cumsum[:, column_index] / time_indexes index_ranks = np.flipud(np.argsort(mean_feature_importances)) chosen_records = np.cumsum(mean_feature_importances[index_ranks]) <= 0.95 chosen_index_ranks = index_ranks[chosen_records] sorted_mean_feature_importances = mean_feature_importances[chosen_index_ranks] sorted_metric_list = np.array(METRIC_LIST)[chosen_index_ranks] remaining = np.sum(mean_feature_importances[index_ranks[~chosen_records]]) print("remaining is {:.4f}.".format(remaining)) sorted_mean_feature_importances = np.hstack((sorted_mean_feature_importances, remaining)) sorted_metric_list = np.hstack((sorted_metric_list, 'others')) pylab.pie(sorted_mean_feature_importances, labels=sorted_metric_list, autopct='%1.1f%%', startangle=0) pylab.axis('equal') pylab.set_cmap('plasma') pylab.show()
def plot_data(plot_type, data, title): ''' This function plots the data. 1) Bar plot: Plots the diabetes prevalence of various age groups in a specific region. 2) Pie chart: Plots the diabetes prevalence by gender. Parameters: plot_type (string): Indicates what plotting function is used. data (dict): Contains the dibetes prevalence of all the contries within a specific region. title (string): Plot title Returns: None ''' plot_type = plot_type.upper() categories = data.keys() # Have the list of age groups gender = ['FEMALE', 'MALE'] # List of the genders used in this dataset if plot_type == 'BAR': # List of population with diabetes per age group and gender female = [data[x][gender[0]] for x in categories] male = [data[x][gender[1]] for x in categories] # Make the bar plots width = 0.35 p1 = pylab.bar([x for x in range(len(categories))], female, width=width) p2 = pylab.bar([x + width for x in range(len(categories))], male, width=width) pylab.legend((p1[0], p2[0]), gender) pylab.title(title) pylab.xlabel('Age Group') pylab.ylabel('Population with Diabetes') # Place the tick between both bar plots pylab.xticks([x + width / 2 for x in range(len(categories))], categories, rotation='vertical') pylab.show() # optionally save the plot to a file; file extension determines file type #pylab.savefig("plot_bar.png") elif plot_type == 'PIE': # total population with diabetes per gender male = sum([data[x][gender[1]] for x in categories]) female = sum([data[x][gender[0]] for x in categories]) pylab.title(title) pylab.pie([female, male], labels=gender, autopct='%1.1f%%') pylab.show()
def plot_single(players, teamnum, teamname): total_matches = 0 matches = {} # matches[player] = number of 1v1 games played info = {} wins = {} for player in players: if player.match: matches[player.character] = 0 wins[player.character] = 0 info[player.character] = (player.league, player.points, player.race) for match in player.match.keys(): total_matches += 1 matches[player.character] += 1 if player.match[match][1]: wins[player.character] += 1 pylab.figure(1, figsize=(8,8)) ax = pylab.axes([0.1, 0.1, 0.8, 0.8]) labels = [] #sorted(matches.keys()) fracs = [] for key in sorted(matches.keys()): labels.append(key + '\n' + info[key][0] + ' ' + info[key][1] + ' (' + info[key][2] + ')\n' \ + str(100 * wins[key]/ matches[key]) + '% win') fracs.append(100.0 * matches[key] / total_matches) #print str(labels) #print str(fracs) #print str(matches) explode = [0] * len(labels) colors = get_colors() pylab.pie(fracs, explode=explode, \ labels=labels, colors=colors, autopct='%1.1f%%', shadow=True) pylab.title('1v1 Games Played ' + teamname) pylab.savefig(os.path.join(SAVEDIR, str(teamnum) + '_1v1games.png'))
def plot_question(fname, question_text, data): import pylab import numpy as np from matplotlib.font_manager import FontProperties from matplotlib.text import Text pylab.figure().clear() pylab.title(question_text) #pylab.xlabel("Verteilung") #pylab.subplot(101) if True or len(data) < 3: width = 0.95 pylab.bar(range(len(data)), [max(y, 0.01) for x, y in data], 0.95, color="g") pylab.xticks([i+0.5*width for i in range(len(data))], [x for x, y in data]) pylab.yticks([0, 10, 20, 30, 40, 50]) #ind = np.arange(len(data)) #pylab.bar(ind, [y for x, y in data], 0.95, color="g") #pylab.ylabel("#") #pylab.ylim(ymax=45) #pylab.ylabel("Antworten") #pylab.xticks(ind+0.5, histo.get_ticks()) #pylab.legend(loc=3, prop=FontProperties(size="smaller")) ##pylab.grid(True) else: pylab.pie([max(y, 0.1) for x, y in data], labels=[x for x, y in data], autopct="%.0f%%") pylab.savefig(fname, format="png", dpi=75)
def pie_packages(**kwargs): gpk = getpackages(**kwargs) n_packages = gpk.count() n_packages_uptodate_main = gpk.filter(n_versions=F('n_packaged')).count() n_packages_uptodate_all = gpk.filter(n_versions=F('n_packaged') + \ F('n_overlay')).count() n_packages_outdated = n_packages - n_packages_uptodate_all n_packages_uptodate_ovl = n_packages_uptodate_all - \ n_packages_uptodate_main pylab.figure(1, figsize=(3.5, 3.5)) if n_packages_uptodate_ovl: labels = 'Ok (gentoo)', 'Ok (overlays)', 'Outdated' fracs = [ n_packages_uptodate_main, n_packages_uptodate_ovl, n_packages_outdated ] colors = '#008000', '#0B17FD', '#FF0000' else: labels = 'Ok (gentoo)', 'Outdated' fracs = [n_packages_uptodate_main, n_packages_outdated] colors = '#008000', '#FF0000' pylab.pie(fracs, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True) pylab.title('Packages', bbox={'facecolor': '0.8', 'pad': 5})
def make_lexicon_pie(input_dict, title): e = 0 f = 0 n = 0 l = 0 g = 0 o = 0 for word in input_dict.keys(): label = input_dict[word] if label == "English": e += 1 elif label == "French": f += 1 elif label == "Norse": n += 1 elif label == "Latin": l += 1 elif label == "Greek": g += 1 else: o += 1 total = e + f + n + l + g + o fracs = [o/total, n/total, g/total, l/total, f/total, e/total] labels = 'Other', 'Norse', 'Greek', 'Latin', 'French', 'English' pl.figure(figsize=(6, 6)) pl.axes([0.1, 0.1, 0.8, 0.8]) pl.pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) pl.title(title) pl.show()
def generatePieChart(chartName, chartDataArray): '''generatePieChart will generate and display a pie chart using the provided data and title''' # Generate pie chart from pylab import figure, axes, pie, title, show # Get total number of data points total = len(chartDataArray) slices = [] # Generate list of data "slices" and the quantity associated with each for item in chartDataArray: isNew = True for element in slices: if element[0] == item: element[1] += 1 isNew = False break if isNew: slices.append([item, 1]) # make a square figure and axes figure(1, figsize=(6,6)) ax = axes([0.1, 0.1, 0.8, 0.8]) # The slices will be ordered and plotted counter-clockwise. labels = [ str(x[0]) for x in slices ] fracs = [ 1.0 * x[1] / total for x in slices ] explode = [] for x in range(len(slices)): explode.append(0.05) # Create and show the pie chart pie(fracs, labels=labels, explode=explode, autopct='%1.1f%%', shadow=True, startangle=90) title(chartName, bbox={'facecolor':'0.8', 'pad':5}) show()
def plotMCIPie(all_result_outputs, label=''): mci_merged_data = mergeSamples(all_result_outputs, ['MCI Type', 'Most Common Indel'], data_label='perOligoMCI') mci_common = mci_merged_data.loc[(mci_merged_data['Most Common Indel'] == mci_merged_data['Most Common Indel 2']) & (mci_merged_data['Most Common Indel'] == mci_merged_data['Most Common Indel 3'])] pie_vals, pie_labels = [], [] for mci_type in ALL_LABELS: pie_vals.append(len( mci_common.loc[mci_common['MCI Type'] == mci_type])) pie_labels.append(mci_type) pie_vals.append(len(mci_merged_data) - len(mci_common)) pie_labels.append('Inconsistent\nbetween\nreplicates') PL.figure(figsize=(4, 4)) PL.pie(pie_vals, labels=pie_labels, autopct='%.1f', labeldistance=1.05, startangle=90.0, counterclock=False, colors=COLORS) PL.title('Most frequent\nmutation per gRNA') PL.show(block=False) saveFig('pie_chart_cats_dominant')
def pie_packages(**kwargs): gpk = getpackages(**kwargs) n_packages = gpk.count() n_packages_uptodate_main = gpk.filter(n_versions=F('n_packaged')).count() n_packages_uptodate_all = gpk.filter(n_versions=F('n_packaged') + \ F('n_overlay')).count() n_packages_outdated = n_packages - n_packages_uptodate_all n_packages_uptodate_ovl = n_packages_uptodate_all - \ n_packages_uptodate_main pylab.figure(1, figsize=(3.5, 3.5)) if n_packages_uptodate_ovl: labels = 'Ok (gentoo)', 'Ok (overlays)', 'Outdated' fracs = [n_packages_uptodate_main, n_packages_uptodate_ovl, n_packages_outdated] colors = '#008000', '#0B17FD', '#FF0000' else: labels = 'Ok (gentoo)', 'Outdated' fracs = [n_packages_uptodate_main, n_packages_outdated] colors = '#008000', '#FF0000' pylab.pie(fracs, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True) pylab.title('Packages', bbox={'facecolor': '0.8', 'pad': 5})
def violations_pie(): valid_places = [row for row in food_data if row['Violations'] !='' and 'No' not in row['Results'] and 'Not' not in row['Results'] and 'Out' not in row['Results']] problems = {} valid_places.sort(key =lambda r: r['DBA Name']) places_group = groupby(valid_places, key =lambda r: r['DBA Name']) for place,group in places_group: all_viols ="" for row in group: all_viols += row['Violations']+'|' l = all_viols.split('|') l=[item.strip() for item in l] problems[place] = len(l) import operator sorted_list= sorted(problems.items(), key= operator.itemgetter(1), reverse=True ) sorted_list =sorted_list[:5] print type(sorted_list) pie_parts=[] labels = [] for item in sorted_list: labels.append(item[0]) pie_parts.append(item[1]) import pylab pylab.pie(pie_parts, labels=labels, autopct='%0.1f%%') pylab.show()
def load_pie_SV(TW_dstk): sum = 0 soBuoi = 0 count = 0 for row in range(TW_dstk.rowCount()): sum = sum + int(TW_dstk.item(row, 3).text()) soBuoi = soBuoi + int(TW_dstk.item(row, 4).text()) count = count + 1 print(soBuoi) try: percent = (sum / soBuoi) * 100 except: return "Chưa có sinh viên" percents = [percent, 100 - percent] programming = [ "Vắng: " + str(round(percent, 2)) + "%", "Có mặt: " + str(round(100 - percent, 2)) + "%" ] explode = [0.1, 0] pylab.pie(percents, labels=programming, explode=explode, shadow=True, startangle=45) pylab.legend(title="Biểu đồ tỉ lệ vắng học", ) pylab.show()
def plotMergedPieDataWithAmbig(all_result_outputs, label='', norm='I1 Total'): pie_labels = [ 'I1_Rpt Left Reads - NonAmb', 'Ambiguous Rpt Reads', 'I1_Rpt Right Reads - NonAmb', 'I1_NonRpt Reads' ] merged_data = mergeSamples(all_result_outputs, pie_labels + [norm], data_label='i1IndelData', merge_on=['Oligo Id']) labels = [ 'Repeated\nleft nucleotide', 'Ambiguous\n(Left = Right)', 'Repeated\nright nucleotide', 'Non-repeated\nnucleotide' ] pie_data = { x: (merged_data[x + ' Sum'] * 100.0 / merged_data[norm + ' Sum']).mean(axis=0) for x in pie_labels } PL.figure(figsize=(3, 3)) PL.pie([pie_data[x] for x in pie_labels], labels=labels, autopct='%.1f', labeldistance=1.05, startangle=120.0, counterclock=False) PL.title('Single nucleotide insertions (I1)') PL.show(block=False) saveFig('ambig_pie')
def pie_graph(start_time,end_time,groupby,generate,**kwargs): start = time.time() graph_data = retrieve_date(start_time,end_time,groupby,generate,**kwargs) data_dict = Counter() for key,columns in graph_data: data_dict[columns[groupby]] +=columns[generate] #print columns[groupby],columns[generate] #pairs = zip(groupby_list,sum_generate_list) pairs = data_dict.items() pairs.sort(key=lambda x:x[1],reverse=True) groupby_list,sum_generate_list = zip(*pairs) groupby_list = list(groupby_list) sum_generate_list = list(sum_generate_list) #print type(groupby_list),type(sum_generate_list) if len(groupby_list)>10: groupby_list = groupby_list[:10] groupby_list.extend(['']*(len(sum_generate_list)-10)) end = time.time() def my_display( x ): if x > 5: return '%.1f' % x + '%' else: return "" explode=[.0]*len(groupby_list) explode[0] = 0 pylab.figure() pylab.pie(sum_generate_list,labels=groupby_list,autopct=my_display,shadow=False,explode=explode) pylab.title('%s groupby %s from %s to %s'%(generate,groupby,start_time,end_time)) pylab.xlabel('Processing time is: %.5ss'%(end-start)) pylab.savefig('foo.png') imgData = cStringIO.StringIO() pylab.savefig(imgData, format='png') imgData.seek(0) pylab.close() return imgData
def displayMHSim(simResults): stickWins, switchWins = simResults pylab.pie([stickWins, switchWins], colors=['r', 'g'], labels=['stick', 'change'], autopct='%.2f%%') pylab.title('To Switch or Not to Switch')
def plot_pie(counter, title, filename): counter = collapse_insignificant(counter) print("counter for", title, "has number of keys:", len(counter.keys())) # make a square figure and axes pylab.figure(1, figsize=(6, 6)) ax = pylab.axes([0.1, 0.1, 0.8, 0.8]) # The slices will be ordered and plotted counter-clockwise. labels = counter.keys() fracs = [count for field_value, count in counter.items()] pylab.pie(fracs, labels=labels, autopct='%1.1f%%', shadow=False, startangle=90) # The default startangle is 0, which would start # the Frogs slice on the x-axis. With startangle=90, # everything is rotated counter-clockwise by 90 degrees, # so the plotting starts on the positive y-axis. pylab.title(title, bbox={'facecolor': '0.8', 'pad': 5}) pylab.savefig(filename, bbox_inches='tight') pylab.close()
def computePieDataWithAmbig(data, label='', norm='I1 Total'): merged_data = mergeWithIndelData(data) pie_labels = [ 'I1_Rpt Left Reads - NonAmb', 'Ambiguous Rpt Reads', 'I1_Rpt Right Reads - NonAmb', 'I1_NonRpt Reads' ] labels = [ 'Repeated\nleft nucleotide', 'Ambiguous\n(Left = Right)', 'Repeated\nright nucleotide', 'Non-repeated\nnucleotide' ] pie_data = { x: (merged_data[x] * 100.0 / merged_data[norm]).mean(axis=0) for x in pie_labels } PL.figure(figsize=(3, 3)) PL.pie([pie_data[x] for x in pie_labels], labels=labels, autopct='%.1f', labeldistance=1.05, startangle=120.0, counterclock=False) PL.title('Single nucleotide insertions (I1)') PL.show(block=False) saveFig('ambig_pie_%s' % label) return pie_data, pie_labels, data['Total reads'].median()
def results_pie(): valid_places = [ row for row in food_data if 'No' not in row['Results'] and 'Not' not in row['Results'] and 'Out' not in row['Results'] ] total = len(valid_places) count = {} for place in valid_places: res = place['Results'] if res not in count.keys(): count[res] = 1 else: count[res] += 1 for key, value in count.items(): print key, value pie_parts = [] labels = [] for key, value in count.items(): labels.append(key) pie_parts.append(value) import pylab pylab.pie(pie_parts, labels=labels, autopct='%0.1f%%') pylab.show()
def violations_pie(): valid_places = [ row for row in food_data if row['Violations'] != '' and 'No' not in row['Results'] and 'Not' not in row['Results'] and 'Out' not in row['Results'] ] problems = {} valid_places.sort(key=lambda r: r['DBA Name']) places_group = groupby(valid_places, key=lambda r: r['DBA Name']) for place, group in places_group: all_viols = "" for row in group: all_viols += row['Violations'] + '|' l = all_viols.split('|') l = [item.strip() for item in l] problems[place] = len(l) import operator sorted_list = sorted(problems.items(), key=operator.itemgetter(1), reverse=True) sorted_list = sorted_list[:5] print type(sorted_list) pie_parts = [] labels = [] for item in sorted_list: labels.append(item[0]) pie_parts.append(item[1]) import pylab pylab.pie(pie_parts, labels=labels, autopct='%0.1f%%') pylab.show()
def Main(): options, _ = MakeOpts().parse_args(sys.argv) assert options.genes_filename and options.counts_filename assert options.output_filename print 'Reading genes list from', options.genes_filename gene_ids = util.ReadProteinIDs(options.genes_filename) print 'Reading protein data from', options.counts_filename gene_counts = util.ReadProteinCounts(options.counts_filename) total = sum(gene_counts.values()) print 'total count', total counts = {} for gene_id, name, count in util.ExtractCounts(gene_counts, gene_ids): counts[name] = counts.get(name, 0) + count array_counts = pylab.array(counts.values()) pcts = array_counts * 100 / total pct = sum(pcts) print 'Category makes up %.2f%% of total protein' % pct print 'Writing output CSV file to', options.output_filename names = sorted(set(gene_ids.values())) f = open(options.output_filename, 'w') w = csv.writer(f) for n in names: w.writerow([n, counts.get(n, 0)]) f.close() fig1 = pylab.figure(0) counts_w_names = sorted([(c, n) for n,c in gene_counts.iteritems()], reverse=True) counts_in_set = [(i, t[0]) for i, t in enumerate(counts_w_names) if t[1] in gene_ids] set_idx = [t[0] for t in counts_in_set] set_counts = [t[1] for t in counts_in_set] all_counts = [t[0] for t in counts_w_names] max_counts = min(500, len(all_counts)) pylab.gca().set_yscale('log') pylab.bar(range(max_counts), all_counts[:max_counts], color='g', edgecolor='g', width=2.0, figure=fig1) pylab.bar(set_idx, set_counts, color='r', figure=fig1, width=2.0) pylab.xlim(0, max_counts) fig2 = pylab.figure(1) pie_labels = sorted(counts.keys()) colormap = ColorMap(pie_labels) colors = [colormap[l] for l in pie_labels] all_counts = [counts[k] for k in pie_labels] pylab.pie(all_counts, labels=pie_labels, colors=colors) for label in pie_labels: print label for count in all_counts: print count * 100.0 / total pylab.show()
def genGraph(self, labels, data, g_title, nme, v=1, id=0): vals = [0, 0, 0] leave_room = 0 for i in range(len(data[0])): if not int(data[v][i]): vals[0] += 1 elif not int(data[0][i]) and int(data[v][i]): vals[1] += 1 else: vals[2] += 1 if ((i + 1) < len(data[0]) and data[0][i] == 0 and data[0][i + 1] == 1): leave_room = leave_room + 1 minutes = float((vals[2] * 5) / 60) on = float((vals[1] + vals[2]) * 5 / 60) figure(id, figsize=(6, 6)) ax = axes([0.1, 0.1, 0.8, 0.8]) vals_total = sum(vals) fracs = [float(val / vals_total) for val in vals] pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True) title(g_title, bbox={'facecolor': '0.8', 'pad': 5}) # show() pylab.savefig(nme) return minutes, on, leave_room
def displayMHSim(simResults, title): stickWins, switchWins = simResults pylab.pie([stickWins, switchWins], colors = ['r', 'c'], labels = ['stick', 'change'], autopct = '%.2f%%') pylab.title(title)
def load_pie(TW_dstk, tru): sum = 0 count = 0 for row in range(TW_dstk.rowCount()): sum = sum + int(TW_dstk.item(row, int(tru) - 1).text()) count = count + 1 sdd = int(TW_dstk.columnCount()) - int(tru) print(sdd) try: percent = (sum / (count * sdd)) * 100 except: return "Chưa có sinh viên" percents = [percent, 100 - percent] programming = [ "Vắng: " + str(round(percent, 2)) + "%", "Có mặt: " + str(round(100 - percent, 2)) + "%" ] explode = [0.1, 0] pylab.pie( percents, labels=programming, explode=explode, ) pylab.title("Biểu đồ tỉ lệ vắng học") pylab.show()
def categories_pie_plot(cont,tit): global labels sizes = [cont[l] for l in labels] pl.pie(sizes, explode=(0, 0, 0, 0), labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) pl.title(tit) pl.show()
def make_graph(users, data): labels = "Jesse","Sebastiaan" ax = pylab.axes([0.1, 0.1, 0.8, 0.8]) pylab.pie(data, labels=labels, autopct='%1.1f%%', shadow=True) pylab.title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5}) #plt.show() pylab.savefig("temp.png")
def displayMHSim(simResults, title): stickWins, switchWins = simResults pylab.pie([stickWins, switchWins], colors=['r', 'c'], labels=['stick', 'change'], autopct='%.2f%%') pylab.title(title)
def create_pie_chart(self, snapshot, filename=''): """ Create a pie chart that depicts the distribution of the allocated memory for a given `snapshot`. The chart is saved to `filename`. """ try: from pylab import figure, title, pie, axes, savefig from pylab import sum as pylab_sum except ImportError: return self.nopylab_msg % ("pie_chart") # Don't bother illustrating a pie without pieces. if not snapshot.tracked_total: return '' classlist = [] sizelist = [] for k, v in list(snapshot.classes.items()): if v['pct'] > 3.0: classlist.append(k) sizelist.append(v['sum']) sizelist.insert(0, snapshot.asizeof_total - pylab_sum(sizelist)) classlist.insert(0, 'Other') #sizelist = [x*0.01 for x in sizelist] title("Snapshot (%s) Memory Distribution" % (snapshot.desc)) figure(figsize=(8, 8)) axes([0.1, 0.1, 0.8, 0.8]) pie(sizelist, labels=classlist) savefig(filename, dpi=50) return self.chart_tag % (self.relative_path(filename))
def plotdu(): stats = diskused() figure(1, figsize=(7,7)) ax = axes([0.1, 0.1, 0.8, 0.8]) stage = os.environ['STAGE'] id = subprocess.Popen('du -s '+stage+'/data/'+os.uname()[1]+'_data0/*', shell=True, stdout=subprocess.PIPE) duout = id.stdout.readlines() p = subprocess.Popen('ls '+stage+'/data/'+os.uname()[1]+'_data0/', shell=True, stdout=subprocess.PIPE) out = p.stdout.readlines() labels = ['free'] dubyid = [stats['kb-free']] for i in range(0, len(out)): labels.append(out[i].split('\n')[0]) dubyid.append(int(duout[i].split('\t')[0])) labels.append(os.uname()[1]+'_odexport/') od = subprocess.Popen('du -s '+stage+'/data/'+os.uname()[1]+'_odexport/', shell=True, stdout=subprocess.PIPE) odout = od.stdout.readlines() dubyid.append(int(odout[0].split('\t')[0])) fracs = dubyid #explode=(0, 0.05, 0, 0) pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True) title(stats['project']+' Allocation', bbox={'facecolor':'0.8', 'pad':5}) show()
def plot_water_usage(state_list, state): # plot_water_usage function ''' Creates a list "y" containing the water usage in Mgal/d of all counties. Y should have a length of 5. The list "y" is used to create a pie chart displaying the water distribution of the five groups. ''' # accumulate public, domestic, industrial, irrigation, and livestock data y = [0, 0, 0, 0, 0] for item in state_list: # Loops through each element in state_list y[0] += item[5] # Public y[1] += item[6] # Domestic y[2] += item[7] # Industrial y[3] += item[8] # Irrigation y[4] += item[9] # Livestock data total = sum(y) # Total of water usage y = [round(x / total * 100, 2) for x in y] # Computes the percentages. color_list = ['b', 'g', 'r', 'c', 'm'] # Colors graph pylab.title(state) # Formats title pylab.pie(y, labels=USERS, colors=color_list) # Graph pylab.show() # Plot pylab.savefig("plot.png") # Saves graph
def plotPie(self,iFig=0): iFig = self.nextIFig(iFig) pl.figure(iFig, figsize=self.figSizePie) labCounts = self.mod.sampLabelCounts() keys = sorted(labCounts.keys()) pl.pie([ labCounts[l] for l in keys ], labels=keys, colors=[ self.labColorMap[l] for l in keys ], autopct='%1.1f%%', shadow=True) pl.savefig(self.figFileName(iFig))
def graphPie(self, figure_number): ''' Dibuja un grafico circular, debe darsele el número de la figura para evitar colisiones ''' pylab.figure(figure_number, figsize=(8,8), facecolor='white') pylab.title(self.mode[0][self.index]) pylab.pie(self.getDict().values(), labels = self.getDict().keys(), autopct='%1.1f%%') pylab.show()
def showTable(labellist, num_list, title_name = u'测试结果'): # make a square figure and axes figure(1, figsize=(6,6)) # ax = axes([0.1, 0.1, 0.8, 0.8]) # explode=(0, 0.05, 0, 0) pie(num_list, labels=labellist, autopct='%1.1f%%', shadow=True) title(title_name, bbox={'facecolor':'0.8', 'pad':5}) show()
def piechart(dictionary): '''creates a piechart from a dictionary dictionary={label:frac}''' labels=[] fracs=[] for key in dictionary: labels.append(key) fracs.append(dictionary[key]) p.pie(fracs,labels=labels) return True
def plotInfo(self): labels = 'Available', 'Busy', 'Away', 'Ofline' explode=(0, 0.05, 0, 0) fracs = [self.availableDuration/StalkingDuration, self.busyDuration/StalkingDuration, self.awayDuration/StalkingDuration, self.offlineDuration/StalkingDuration] print fracs plt.pie(fracs, explode=explode, labels = labels,autopct='%1.1f%%', shadow=True, startangle=90) plt.title('Stalking results') plt.show()
def plot_event_chain_summaries_pie_charts(data, type): pylab.title('Distribution of %s Event Chains\n' % type) outFile = outDir + 'eventChainSummary-pie-chart-%s'%type labels = '1', '2', '3', '4', '>=5' percentages = data.astype(float)/float(np.sum(data)) pylab.pie(percentages, labels=labels, colors=colors, autopct='%1.1f%%') pylab.axis('equal') display_graph(outFile) return
def piechart(dictionary): '''creates a piechart from a dictionary dictionary={label:frac}''' labels = [] fracs = [] for key in dictionary: labels.append(key) fracs.append(dictionary[key]) p.pie(fracs, labels=labels) return True
def plotPieChart(data, x_axis): # plots a pie chart: raw = data.getColumnFromHeader(x_axis) print raw schoolName = data.getArray().transpose()[0][2::] print len(schoolName) plt.pie(raw, labels=schoolName) plt.title(x_axis) plt.show()
def pie_comparison(data, plot_title=""): ax = pylab.axes([0.1, 0.1, 0.8, 0.8]) pylab.figure(1, figsize=(6, 6)) pylab.title(plot_title, bbox={'facecolor': '0.8', 'pad': 5}) sorted_data = sorted(data, key=lambda x: x[1]) fracs = [x[1] for x in sorted_data] labels = [contour.Contour(x[0]) for x in sorted_data] pylab.pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True) pylab.show()
def pieDiagramm(counterDataframe, Filename): colName = counterDataframe.columns[0] xWerte = counterDataframe['Anzahl'].values label = counterDataframe[colName].values pl.axis("equal") # Kreisdiagramm rund gestaltet (sonst Standard: oval!) pl.pie(xWerte, labels=label, autopct="%1.1f%%") pl.savefig(Filename, format='jpg', dpi=900) pl.show()
def computeFractionWithI1Repeats(data, label=''): merged_data = mergeWithIndelData(data) pie_label = 'Oligos with I1 Repeats' perc_with_11Rpt = len(merged_data.loc[(merged_data['I1_Rpt Left Reads - NonAmb'] + merged_data['Ambiguous Rpt Reads'])> 0.0])*100.0/len(merged_data) pie_data = {pie_label:perc_with_11Rpt} PL.figure() PL.pie([perc_with_11Rpt, 1-perc_with_11Rpt], labels=[pie_label,'Oligos without I1 Repeats'], autopct='%.1f', labeldistance=1.05, startangle=90.0, counterclock=False) PL.title(label) PL.show(block=False) return pie_data, [pie_label], merged_data['Total reads'].median()
def dept_spend(self): out = self.a.extract_dept_spend() # delete very small items for k in out.keys(): if out[k] < 2000: # anything less than 2 billion del out[k] labels = out.keys() # labels = [ l.replace(' ', '\n') for l in labels ] pylab.figure(figsize=(12, 12)) pylab.pie(out.values(), labels=labels, labeldistance=1.3) pylab.savefig('dept_expenditure.png')