我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.pie()。
def pieGraphics(Labels,ValueList,graphicTitle='??'): colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', "blue","green","cyan","magenta"] maxdata = max(ValueList) explode = [] for v in ValueList: if v == maxdata: explode.append(0.1) else: explode.append(0) print(explode) patches,l_text,p_text = plt.pie(ValueList, labels=Labels, colors=colors,autopct='%1.1f%%',explode=explode ,shadow=True, startangle=90) for font in l_text: font.set_fontproperties(FontProperties(fname=PATH_SUFFIX+'SIMLI.TTF')) plt.title(graphicTitle,fontproperties=font_set,y=1.05) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') plt.show()
def pieGraphics(Labels,ValueList,graphicTitle='??'): # The slices will be ordered and plotted counter-clockwise. #labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' #sizes = [15, 30, 45, 10] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', "blue","green","cyan","magenta"] explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') plt.pie(ValueList, labels=Labels, colors=colors,autopct='%1.1f%%', shadow=True, startangle=90) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') plt.show() #barGraphics('??','??',['A','B','C','D','E','F'],[29,30,40,47,38,23],'????') #linePlotGraphics("xLabel","yLabel",[1,2,3,4,5,6,7,8,9,10],[1.1,1.9,2.6,3.6,9.8,14,24,40,80,150],graphicTitle='??') #scatterPlotsGraphics("xLabel","yLabel",[1,2,3,4,5,6,7,8,9,10],[1,11.9,2,6.3,6,9.8,14,4,8,5],graphicTitle='??')
def bin(): labels = 'A', 'B', 'C', 'D' fracs = [15, 30.55, 44.44, 10] explode = [0, 0.1, 0, 0] # 0.1 ?????? plt.axes(aspect=1) # set this , Figure is round, otherwise it is an ellipse # autopct ?show percet plt.pie(x=fracs, labels=labels, explode=explode, autopct='%3.1f %%', shadow=True, labeldistance=1.1, startangle=90, pctdistance=0.6 ) ''' labeldistance?????????????1.1?1.1?????? autopct??????????%3.1f%%????????????????? shadow??????? startangle??????0????0?????????????????90??????? pctdistance?????text?????? patches, l_texts, p_texts????????????p_texts????????l_texts???label??? ''' plt.show()
def make_pie_chart(numbers, labels): "Function to make a pie chart" def make_autopct(values): "Nicely label the plot" def my_autopct(pct): total = sum(values) val = int(round(pct*total/100.0)) return '{p:.2f}% ({v:d})'.format(p=pct, v=val) return my_autopct # Plot the pie chart in a figure fig = plt.figure() fig.add_subplot(111, aspect='equal') plt.pie(numbers, labels=labels, autopct=make_autopct(numbers), shadow=True,) plt.show() # Url's in 2016 the 2015 url will probably be simmilar to the 2013, 2014 # and that url will probably point to the 2016
def plot(sizes,plotname): fig = plt.figure(figsize=(2.0,2.0),facecolor='white') ax = plt.subplot(111) psizes = ['%1.1f%%' % (x/sum(sizes)*100) for x in sizes] labels = [x+'\n'+y for x,y in zip(LABELS,psizes)] patches = plt.pie(sizes, colors=COLORS, labels=labels, shadow=False, startangle=90, labeldistance=0.7, wedgeprops={'linewidth': 4}) for pie_wedge in patches[0]: pie_wedge.set_edgecolor('white') for t in patches[1]: t.set_horizontalalignment('center') plt.axis('equal') plt.tight_layout() plt.savefig(plotname) print('saved plot to {}'.format(plotname)) plt.show() ###################################################### # Data processing
def create_chart(self, top, others): plt.clf() sizes = [x[1] for x in top] labels = ["{} {:g}%".format(x[0], x[1]) for x in top] if len(top) >= 10: sizes = sizes + [others] labels = labels + ["Others {:g}%".format(others)] title = plt.title('User activity in the last 5000 messages') title.set_va("top") title.set_ha("left") plt.gca().axis("equal") colors = ['r', 'darkorange', 'gold', 'y', 'olivedrab', 'green', 'darkcyan', 'mediumblue', 'darkblue', 'blueviolet', 'indigo'] pie = plt.pie(sizes, colors=colors, startangle=0) plt.legend(pie[0], labels, bbox_to_anchor=(0.7, 0.5), loc="center", fontsize=10, bbox_transform=plt.gcf().transFigure) plt.subplots_adjust(left=0.0, bottom=0.1, right=0.45) image_object = BytesIO() plt.savefig(image_object, format='PNG') image_object.seek(0) return image_object
def plot_segments_pie(seg, data, phases_colors): """ Plot a pie chart of the percentage of time spent on each segment :param seg: dict dict with list of start, end for each segment :param data: pd.DataFrame the data """ weights = get_weights(seg, data) plt.figure(1, figsize=(10, 10)) labels = list(weights.keys()) fracs = [weights[key] for key in labels] sum_weight = sum(weight for weight in fracs) if sum_weight < 1: fracs.append(1 - sum_weight) labels.append('missing') plot_colors = [phases_colors[name] for name in labels] plt.pie(fracs, labels=labels, colors=plot_colors, autopct='%1.1f%%') plt.title('Temps passé dans chaque phase, en pourcentage de la durée du vol', bbox={'facecolor':'0.8', 'pad':5}) plt.draw() plt.show()
def plot_ports_sides(ports_full_flight, ports_colors): """ Plot one pie chart for each side of the time spent on each port :param ports_full_flight: dict port usage on full filght """ ports_durations = tuples_to_durations(ports_full_flight) _, axarr = plt.subplots(1, 2, figsize=(20, 10)) labels = ports_durations.keys() # pressure ports names for side in [1, 2]: labels_1 = [l for l in labels if l[-1] == str(side)] + ['apu', 'no bleed'] fracs_1 = [ports_durations[key] for key in labels_1] plot_colors = [ports_colors[name] for name in labels_1] axarr[side-1].pie(fracs_1, labels=labels_1, autopct='%1.1f%%', colors=plot_colors) axarr[side-1].set_title('côté '+str(side), bbox={'facecolor':'0.8', 'pad':5}) plt.show()
def plot_ports(ports_full_flight, data, ports_colors): """ Plot a pie chart of the percentage of time spent on each pressure port :param ports_full_flight: dict ports usage for the whole flight :param data: DataFrame data of the flight """ flight_duration = data.Time.iloc[-1] - data.Time.iloc[0] ports_durations = tuples_to_durations(ports_full_flight) # Convert durations on each port into percentage of the flight duration for port in ports_durations.keys(): ports_durations[port] /= flight_duration plt.figure(1, figsize=(10, 10)) labels = ports_durations.keys() fracs = [ports_durations[key] for key in labels] colors = [ports_colors[name] for name in labels] plt.pie(fracs, labels=labels, colors=colors, autopct='%1.1f%%') plt.title('Temps passé sur chaque port, en pourcentage de la durée du vol', bbox={'facecolor':'0.8', 'pad':5}) plt.show()
def pie_plot(): """ pie plot """ # ?????? sizes = [15, 30, 45, 10] explode = [0, 0.05, 0, 0] labels = ["Frogs", "Hogs", "Dogs", "Logs"] colors = ["yellowgreen", "gold", "lightskyblue", "lightcoral"] # ???? plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct="%1.1f%%", shadow=True, startangle=90) plt.axis("equal") # ???? plt.show() return # pie_plot()
def zp_show_pie(results,filename='./2.jpg'): labels = list(results.keys()) values = list(results.values()) colors = ['yellow','red','green','yellowgreen','blue'] draw_colors = [] for i in range(len(values)): draw_colors.append(colors[i%len(colors)]) fig = plt.figure(figsize=(8,8)) plt.pie(values,labels=labels,colors=draw_colors,autopct='%1.2f%%') _set_ch() if filename: fig.savefig(filename) else: fig.show() #???????????????????
def plotPie4Gender(dics): plt.figure(figsize=(6,9)) labels = getLables(dics) sizes = getSizes(dics) colors = ['red','yellowgreen','lightskyblue'] explode = (0.05,0,0) patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance = 1.1,autopct = '%3.1f%%',shadow = False, startangle = 90,pctdistance = 0.6) for t in l_text: t.set_size=(30) for t in p_text: t.set_size=(20) plt.axis('equal') plt.legend() plt.show()
def plotPie4Top5(dics): plt.figure(figsize=(6,9)) labels = getLables(dics) print(labels) sizes = getSizes(dics) colors = ['red','yellowgreen','lightskyblue','green','blue','pink'] explode = (0.05,0,0,0,0) patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance = 1.1,autopct = '%3.1f%%',shadow = False, startangle = 90,pctdistance = 0.6) for t in l_text: t.set_size=(30) for t in p_text: t.set_size=(20) plt.axis('equal') plt.legend() plt.show()
def model_frequency(): """ ???????? """ temp_list = [] with open('rent_ave.csv') as csvfile: reader = [each for each in csv.DictReader(csvfile)] for row in reader: text = row[u'model'] temp_list.append(text) d = Counter(temp_list).most_common(6) a = [unicode(i[0] + '\n({})'.format(i[1]), "utf-8") for i in d] b = [i[1] for i in d] a.append(u'??\n({})'.format(len(reader) - sum(b))) b.append(len(reader) - sum(b)) colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', 'red', 'gray', 'green'] explode = (0.1, 0, 0, 0, 0, 0, 0) plt.pie(b, labels=a, colors=colors, explode=explode, autopct='%1.1f%%', shadow=True) plt.axis('equal') plt.savefig('modelFrequency.png') plt.show()
def score_detail(result): if result is not None: # plt.clf() label_scores = sorted(result["score_detail"].items()) # labels labels = "1?", "2?", "3?", "4?", "5?" # sizes sizes = [pair[1] for pair in label_scores] # explode the_max = max(sizes) the_index = sizes.index(the_max) explode = [0, 0, 0, 0, 0] explode[the_index] = 0.1 explode = tuple(explode) # colors colors = ['yellowgreen', "gold", "lightskyblue", "lightcoral", "blueviolet"] # patches and texts plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct="%1.2f%%", shadow=True, startangle=0) plt.title("????????", loc="left", fontsize=20) plt.axis("equal") plt.show()
def dish_score_detail(result): if result is not None: # plt.clf() label_scores = result["dish_score"] # labels labels = "1?", "2?", "3?", "4?", "5?" # sizes sizes = [label_scores.count(i) for i in range(5)] # explode the_max = max(sizes) the_index = sizes.index(the_max) explode = [0, 0, 0, 0, 0] explode[the_index] = 0.1 explode = tuple(explode) # colors colors = ['yellowgreen', "gold", "lightskyblue", "lightcoral", "blueviolet"] # patches and texts plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct="%1.2f%%", shadow=True, startangle=0) plt.title("????????", loc="left", fontsize=20) plt.axis("equal") plt.show()
def service_score_detail(result): if result is not None: # plt.clf() label_scores = result["service_score"] # labels labels = "1?", "2?", "3?", "4?", "5?" # sizes sizes = [label_scores.count(i) for i in range(5)] # explode the_max = max(sizes) the_index = sizes.index(the_max) explode = [0, 0, 0, 0, 0] explode[the_index] = 0.1 explode = tuple(explode) # colors colors = ['yellowgreen', "gold", "lightskyblue", "lightcoral", "blueviolet"] # patches and texts plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct="%1.2f%%", shadow=True, startangle=0) plt.title("????????", loc="left", fontsize=20) plt.axis("equal") plt.show()
def s_from(result): if result is not None: # plt.clf() sfrom = result["sfrom"] # title title = "??????" # total sources sources = tuple(set(sfrom)) # size sizes = [sfrom.count(source) for source in sources] # colors colors = ['yellowgreen', "gold", "lightskyblue", "lightcoral", "blueviolet"] # pie plt.pie(sizes, labels=sources, colors=colors, autopct="%1.2f%%", shadow=True, startangle=0) plt.title(title, loc="left", fontsize=20) plt.axis("equal") plt.show()
def pie(orderDict, outname): sizes = orderDict.values() total = sum(sizes) labels = [] for i in orderDict.keys(): perct = orderDict[i] / float(total) labels.append("%s: %i (%s)" % (i,int(orderDict[i]),percentage_format(perct,1))) colors = get_colors(len(labels)) plt.figure(figsize=(8,6)) patches, text = plt.pie(sizes, startangle=90,colors=colors) plt.legend(patches,labels,loc=4,bbox_to_anchor=(1, 0),fontsize=15) plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.tight_layout() plt.savefig(outname + "_ORFs_category.pdf") plt.close()
def analysis_mobile(self): # self.record_result('<strong style="color: black; font-size: 24px;">???????????????...</strong>') fig_size = plt.rcParams["figure.figsize"] plt.figure(figsize = (2.4, 2.4)) obj = self.data_frame['is_mobile'] obj = obj.value_counts() obj = obj.rename({1: '???', 0: 'PC'}) plt.pie(x = obj.values, autopct = '%.0f%%', radius = 0.7, labels = obj.index, startangle = 180) plt.title('?????/ PC ????') plt.tight_layout() filename = '%s_mobile.png' % self.product_id plt.savefig('%s/%s' % (utils.get_save_image_path(), filename)) plt.figure(figsize = fig_size) plt.clf() result = utils.get_image_src(filename = filename) self.record_result(result, type = 'image') # ????????????
def Energy_Participation(Energy_Flow): Energy_Participation = {'Energy PV':0, 'Energy Diesel':0, 'Discharge energy from the Battery':0, 'Lost Load':0} c = {'Energy Diesel':'Diesel Generator', 'Discharge energy from the Battery':'Battery', 'Energy PV':'From PV', 'Lost Load':'Lost Load'} labels=[] for v in Energy_Participation.keys(): if Energy_Flow[v]/Energy_Flow['Energy_Demand'] >= 0.001: Energy_Participation[v] = Energy_Flow[v]/Energy_Flow['Energy_Demand'] labels.append(c[v]) else: del Energy_Participation[v] Colors=['r','c','b','k'] plt.figure() plt.pie(Energy_Participation.values(), autopct='%1.1f%%', colors=Colors) Handles = [] for t in range(len(labels)): Handles.append(mpatches.Patch(color=Colors[t], alpha=1, label=labels[t])) plt.legend(handles=Handles, bbox_to_anchor=(1.4, 1)) plt.savefig('Results/Energy_Participation.png', bbox_inches='tight') plt.show() return Energy_Participation
def plot_pie(counter, label, plot=None): import matplotlib.pyplot as plt plt.figure() nums = list(counter.keys()) counts = list(counter.values()) plt.pie(counts, labels=nums, autopct="%1.1f%%", counterclock=True, wedgeprops={"edgecolor": "white"}) plt.axis("equal") if plot: plt.savefig(plot + "pie_" + label + ".png") else: plt.show()
def personal_money(): baidu_current = 2619 baidu_fix = 50000 jd = 19284 lujinsuo = 43998 icbc = 455 cmb = 77 zhifubao = 0 stock_ht = 53200 stock_gj = 19112 fund = 3515 qq = 1000 X = [baidu_current + baidu_fix, jd, lujinsuo, icbc, cmb, stock_ht, stock_gj, fund, qq] labels = [u'??', u'??', u'???', u'??', u'??', u'??', u'??', u'??', u'QQ'] plt.figure() plt.subplot(2, 1, 1) p = plt.pie(X, labels=labels, autopct='%1.1f' ) print p # plt.show() print p[1] # ?????? for font in p[1]: font.set_fontproperties(mpl.font_manager.FontProperties( fname='C:/Windows/winsxs/amd64_microsoft-windows-font-truetype-simfang_31bf3856ad364e35_6.1.7600.16385_none_e417159f3b4eb1b7/simfang.ttf')) plt.subplot(2, 1, 2) x2 = [baidu_fix + baidu_current + jd + lujinsuo + icbc + cmb + qq, fund + stock_gj + stock_ht] print x2 labels2 = [u'??', u'??'] p2 = plt.pie(x2, labels=labels2,autopct='%1.1f') for font2 in p2[1]: font2.set_fontproperties(mpl.font_manager.FontProperties( fname='C:/Windows/winsxs/amd64_microsoft-windows-font-truetype-simfang_31bf3856ad364e35_6.1.7600.16385_none_e417159f3b4eb1b7/simfang.ttf')) plt.show()
def line_define(): labels='frogs','hogs','dogs','logs' sizes=15,20,45,10 colors='yellowgreen','gold','lightskyblue','lightcoral' explode=0,0.1,0,0 #?????? plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50) plt.axis('equal') plt.show()
def pie_test(): plt.figure() x=[1,1,3] plt.pie(x) plt.show()
def main(subfile,plotname): # read in ground truth, and plot the distribution # of the top scores for each class sub = loadfile(subfile) subdict = dict(sub) with open(GTFILE) as f: reader = csv.DictReader(f) for row in reader: aid = row['id'] length = float(row['length']) Nframes = FPS*int(length) actions = parse_actions(row['actions']) frames = np.linspace(0,length,25) framenumber = np.linspace(0,Nframes,25) for f,sec,fnum in zip(range(1,26),frames,framenumber): analyze(subdict,actions,aid,f,sec,fnum) pies = [] for c in range(157): scores = det[c] scores.sort(key=lambda x: -x[2]) scores = scores[:100] # pick the top 100 scores for this class tp = sum(1 for x in scores if x[4]=='tp') bnd = sum(1 for x in scores if x[4]=='bnd') fb = sum(1 for x in scores if x[4]=='fb') obj = fb/2.+sum(1 for x in scores if x[4]=='obj') vrb = fb/2.+sum(1 for x in scores if x[4]=='vrb') fo = sum(1 for x in scores if x[4]=='fo') fp = sum(1 for x in scores if x[4]=='fp') pie = [tp, bnd, obj, vrb, fo, fp] pies.append(pie) sizes = [sum(x) for x in zip(*pies)] #combine results for all classes plot(sizes,plotname)
def chatchart(self, ctx): """ Generates a pie chart, representing the last 5000 messages in this channel. """ channel = ctx.message.channel e = discord.Embed(description="Loading...", colour=0x00ccff) e.set_thumbnail(url="https://i.imgur.com/vSp4xRk.gif") em = await self.bot.say(embed=e) history = [] async for msg in self.bot.logs_from(channel, 5000): history.append(msg) msg_data = {'total count': 0, 'users': {}} for msg in history: if msg.author.bot: pass elif msg.author.name in msg_data['users']: msg_data['users'][msg.author.name]['msgcount'] += 1 msg_data['total count'] += 1 else: msg_data['users'][msg.author.name] = {} msg_data['users'][msg.author.name]['msgcount'] = 1 msg_data['total count'] += 1 for usr in msg_data['users']: pd = float(msg_data['users'][usr]['msgcount']) / float(msg_data['total count']) msg_data['users'][usr]['percent'] = round(pd * 100, 1) top_ten = heapq.nlargest(10, [(x, msg_data['users'][x][y]) for x in msg_data['users'] for y in msg_data['users'][x] if y == 'percent'], key=lambda x: x[1]) others = 100 - sum(x[1] for x in top_ten) img = self.create_chart(top_ten, others) await self.bot.delete_message(em) await self.bot.send_file(channel, img, filename="chart.png")
def charts(): # basic pie chart, distribution of protocols - concept for placing images global global_proto fig = plt.figure() labels = global_proto.keys() sizes = global_proto.values() plt.pie(sizes, labels=labels) plt.axis('equal') figdata = BytesIO() fig.savefig(figdata, format='png') content = """\ <img src="data:image/png;base64, """ + base64.b64encode(figdata.getvalue()).decode('utf-8') + """\ "></img>""" return template('honeyd/utilities/http/index.html', data=content)
def plot_ports_seg(raw_ports, ports_colors): """ For each phase, plot one pie chart for each side of the time spent on each port :param ports: dict ports usage for each segments """ ports = {} for each_segment, ports_on_segment in raw_ports.items(): ports[each_segment] = tuples_to_durations(ports_on_segment) f, axarr = plt.subplots(2, 7, figsize=(23, 7)) f.suptitle('Utilisation des ports selon chaque phase', bbox={'facecolor':'0.8', 'pad':5}) j = 0 for each_segment in ports: labels = ports[each_segment].keys() # pressure ports names # left pressure ports + apu labels_1 = [l for l in labels if l[-1] == '1'] + ['apu', 'no bleed'] # right pressure ports + apu labels_2 = [l for l in labels if l[-1] == '2'] + ['apu', 'no bleed'] fracs_1 = [ports[each_segment][key] for key in labels_1] fracs_2 = [ports[each_segment][key] for key in labels_2] colors_1 = [ports_colors[name] for name in labels_1] colors_2 = [ports_colors[name] for name in labels_2] axarr[0, j].pie(fracs_1, labels=labels_1, colors=colors_1, autopct='%1.1f%%') axarr[0, j].set_title('{} côté 1'.format(each_segment), bbox={'facecolor':'0.8', 'pad':5}) axarr[1, j].pie(fracs_2, labels=labels_2, colors=colors_2, autopct='%1.1f%%') axarr[1, j].set_title('{} côté 2'.format(each_segment), bbox={'facecolor':'0.8', 'pad':5}) j = (j+1)%7 plt.show()
def get_pie_data(self, data): ''' Return the labels and sizes needed for the pie chart ''' labels = [v[0] for v in data] sizes = [v[1] for v in data] return labels, sizes
def plot_pie(self, key, data=None): ''' Makes a matplotlib pie chart for a given tag key ''' if self.tagvals and key in self.tagvals: vals = self.tagvals[key] labels = [v['name'] for v in vals] sizes = [v['count'] for v in vals] elif key == 'place': assert data is not None, 'Must provide some data to extract' vals = self.count_data(data) labels, sizes = self.get_pie_data(vals) elif key == 'baseurl': vals = self.tagvals['url'] names = [v['name'] for v in vals] labels = set(['sas' if 'sas.sdss.org' in n else 'api' for n in names]) stats = [{'type': 'web' if l == 'sas' else l, 'count': sum(d['count'] for d in vals if l in d['name'])} for l in set(labels)] labels = [s['type'] for s in stats] sizes = [s['count'] for s in stats] else: sizes = None raise NameError('No sizes or labels found. Make sure the data is somewhere') plt.clf() plt.pie(sizes, labels=labels, shadow=True, autopct='%1.1f%%', startangle=90) plt.axis('equal') plt.tight_layout() plt.show()
def pieChart(dlist, explode, labels, title): plt.pie(dlist, explode=explode, labels=labels, autopct='%1.1f%%', startangle=90) plt.axis('equal') plt.title('Parameter Comparison of '+title) plt.show()
def display_result(data_dict, confidence, username, tag_name): plt.figure(figsize=(9, 9)) labels = ['family', 'sport', 'animal', 'art', 'technology', 'life', 'fashion', 'food', 'travel'] colors = ['green', 'blue', 'cyan', 'purple', 'orange', 'pink', 'seagreen', 'red', 'yellow'] sizes = list() explode_list = list() max_label = '' current_value = 0 total_value = 0 for label in labels: sizes.append(data_dict[label]) total_value += data_dict[label] if data_dict[label] > current_value: current_value = data_dict[label] max_label = label for label in labels: if label == max_label: explode_list.append(0.1) else: explode_list.append(0) final_sizes = list() if total_value == 0: return for size in sizes: final_sizes.append(size/total_value) explode = tuple(explode_list) patches, l_text, p_text = plt.pie(final_sizes, explode=explode, labels=labels, colors=colors, autopct='%3.1f%%', shadow=False, startangle=90, pctdistance=0.7) for t in l_text: t.set_size = 12 for t in p_text: t.set_size = 4 plt.axis('equal') plt.text(-1.2, 1.2, 'username: ' + username, fontsize=15) plt.text(-1.2, 1.1, 'confidence: %.2f%%' % (confidence * 100), fontsize=15) file_name = 'tag_analysis_result/' + tag_name + '/samples/' + username + '_analysis.png' plt.savefig(file_name, format='png') # This function is used to visualize the analysis overall result of this tag. Basically, we use matplotlib to do the # work and the result will be stored as a png file.
def display_tag_result(data_dict, confidence, tag_name): plt.figure(figsize=(9, 9)) labels = ['family', 'sport', 'animal', 'art', 'technology', 'life', 'fashion', 'food', 'travel'] colors = ['green', 'blue', 'cyan', 'purple', 'orange', 'pink', 'seagreen', 'red', 'yellow'] sizes = list() explode_list = list() max_label = '' current_value = 0 total_value = 0 for label in labels: sizes.append(data_dict[label]) total_value += data_dict[label] if data_dict[label] > current_value: current_value = data_dict[label] max_label = label for label in labels: if label == max_label: explode_list.append(0.1) else: explode_list.append(0) final_sizes = list() if total_value == 0: return for size in sizes: final_sizes.append(size/total_value) explode = tuple(explode_list) patches, l_text, p_text = plt.pie(final_sizes, explode=explode, labels=labels, colors=colors, autopct='%3.1f%%', shadow=False, startangle=90, pctdistance=0.7) for t in l_text: t.set_size = 12 for t in p_text: t.set_size = 4 plt.axis('equal') plt.text(-1.2, 1.2, 'tag_name: ' + tag_name, fontsize=15) plt.text(-1.2, 1.1, 'confidence: %.2f%%' % (confidence * 100), fontsize=15) file_name = 'tag_analysis_result/' + tag_name + '/' + 'tag_analysis.png' plt.savefig(file_name, format='png') # This function combine our own dictionary into the overall dictionary such that some special words # can be recognised by the function.
def plot_fueltype_stats(df): stats = lookup(df, by='Fueltype') plt.pie(stats, colors=stats.index.to_series().map(tech_colors).tolist(), labels=stats.index, autopct='%1.1f%%')
def savePlot(passFile): plot.tight_layout() plot.savefig(passFile, dpi=96) # Plot a pie chart
def plotPie(passNames, passData): plugins.core.sendOutput('Generating pie chart...', 'stderr') patches, text = plot.pie(passData, shadow=True, startangle=90) plot.axis('equal') plot.legend(patches, passNames, loc='lower left') # Plot a horizontal bar chart
def generate_report(): # The slices will be ordered and plotted counter-clockwise. labels = ['groceries', 'entertainment', 'books', 'shopping'] b = random.randint(2, 98) a = random.randint(1, b - 1) c = random.randint(b + 1, 99) percents = [a, b - a, c - b, 100 - c] print percents colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = (0, 0, 0, 0) # explode a slice if required plt.pie(percents, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False) #draw a circle at the center of pie to make it look like a donut centre_circle = plt.Circle((0,0),0.75,color='black', fc='white',linewidth=1.25) fig = plt.gcf() fig.gca().add_artist(centre_circle) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') fig_name = 'foo{}'.format(random.randint(1,1000000000000)) max_per = max(percents) to_watch = labels[percents.index(max_per)] #### uncomment out when needed fig.savefig(fig_name, dpi=300) return fig_name, to_watch # return "you should watch your spending on {}".format(to_watch) # return fig_name, (max_per, to_watch)
def plot_pie(self): plt.pie(x=self.__fd.values(), labels=self.__fd.keys(), autopct='%1.1f%%', shadow=True) plt.show()
def location(self): Data = pd.DataFrame(self.df, columns=['location']) location = Data.groupby('location').size() # ????? plt.figure() plt.title(u'???????') plt.pie(location,labels=location.index) plt.savefig('location.svg') # ???????
def setup(): commands.add(pie) commands.add(bar) commands.add(histogram) commands.add(latex)
def cost_time(result): if result is not None: # plt.clf() cost_times = result["cost_time"] title = "??????" sources = ("???\n(15min?)", "???\n(15-30min?)", "???\n(30-60min?)", "??\n(60-100min?)", "??????\n(??100min)") sizes = [0] * len(sources) for a_time in cost_times: if a_time <= 15: sizes[0] += 1 elif a_time <= 30: sizes[1] += 1 elif a_time <= 60: sizes[2] += 1 elif a_time <= 100: sizes[3] += 1 else: sizes[4] += 1 colors = ['yellowgreen', "gold", "lightskyblue", "lightcoral", "blueviolet"] # explode the_max = max(sizes) the_index = sizes.index(the_max) explode = [0, 0, 0, 0, 0] explode[the_index] = 0.1 explode = tuple(explode) # pie plt.pie(sizes, labels=sources, colors=colors, explode=explode, autopct="%1.2f%%", shadow=True, startangle=0) plt.title(title, loc="left", fontsize=20) plt.axis("equal") plt.show()
def _change(self, sizes): self.figure.clear() labels = '8.0~8.5', '8.5~9.0', '9.0~9.5', '9.5~10' plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90) plt.axis('equal') self.figure.suptitle("Movie Rate Analyse") self.canvas.show()
def analysis_buy_channel(self): # self.record_result('?????????????', color = 'black', font_size = 24, strong = True) obj = self.data_frame['user_client_show'] obj = obj.value_counts() obj = obj.rename({u'': u'??????'}) # obj = obj.append(mobile_obj) # obj.plot(style = 'ro-') ax = obj.plot(kind = 'bar', alpha = self.opacity, color = self.color) ax.set_xticklabels(obj.index, rotation = 45 if len(obj.index) > 3 else 0) # ????????? count = obj.sum() for i, val in enumerate(obj.values): ax.text(i - 0.25, val, '%.3f%%' % (val * 1.0 / count * 100)) # ???????????????????? # plt.subplot(111) # obj = self.data_frame['is_mobile'] # obj = obj.value_counts() # # obj = obj.rename({1: '???', 0: 'PC'}) # plt.pie(x = obj.values, autopct = '%.0f%%', radius = 0.3, labels = obj.index) plt.title('????????????????') ax.set_xlabel('???') ax.set_ylabel('??') filename = '%s_channel.png' % self.product_id plt.tight_layout() plt.savefig('%s/%s' % (utils.get_save_image_path(), filename)) plt.clf() result = utils.get_image_src(filename = filename) self.record_result(result, type = 'image') # ?????????
def pie(x, label, name, dpi=96): data = sorted(zip(x, label), key=lambda x:x[0], reverse=True) x = [] label = [] for a, b in data: x.append(a) label.append(b) total = sum(x) fracs = [round(v/total*100, 2) for v in x] p = plt.pie(fracs, startangle=90) plt.axis('equal') #Annotations from https://commons.wikimedia.org/wiki/File:PV-Global-2010.svg y1s = [] for p1, l1, f1 in zip(p[0], label, fracs): r = p1.r dr = r*0.1 t1, t2 = p1.theta1, p1.theta2 theta = (t1+t2)/2. xc, yc = r/2.*cos(theta/180.*pi), r/2.*sin(theta/180.*pi) x1, y1 = (r+dr)*cos(theta/180.*pi), (r+dr)*sin(theta/180.*pi) if x1 > 0 : x1 = r+2*dr ha, va = "left", "center" tt = -180 cstyle = "angle,angleA=0,angleB=%f" % (theta,) else: x1 = -(r+2*dr) ha, va = "right", "center" tt = 0 cstyle = "angle,angleA=0,angleB=%f" % (theta,) # Prevent overlapping text y1 = round(y1*10)/10 if any([(abs(y1 - y) < 0.15) for y in y1s]): y1 = max(y1s) + 0.15 l1 = l1 + ': ' + str(f1) + '%' plt.annotate(l1, (xc, yc), xycoords = "data", xytext = (x1, y1), textcoords = "data", ha = ha, va = va, arrowprops=dict(arrowstyle="-", connectionstyle=cstyle, patchB=p1) ) y1s.append(y1) plt.savefig(cache_path(name), dpi=dpi, bbox_inches='tight') plt.close()
def about_sources(corpus, processes, with_bio): """ Items' sources """ def worker(items): sources = defaultdict(int) for doc in items: url = doc.get('url') if not url: logger.warn('found an item without URL, name: %s, bio: %s', doc.get('name'), doc.get('bio', '')[:100] + ' ...') sources['_skipped_'] += 1 continue elif with_bio and len(doc.get('bio') or '') < 5: continue parsed = urlparse(url) if parsed.netloc: sources[parsed.netloc] += 1 else: logger.warn('cannot parse URL: %s', url) sources['_skipped_'] += 1 return sources aggregated_sources = defaultdict(int) corpus = parallel.make_batches(load_scraped_items(corpus), 1000) for sources in parallel.map(worker, corpus, processes): for k, v in sources.iteritems(): aggregated_sources[k] += v aggregated_sources = sorted(aggregated_sources.items(), key=lambda (_, v): v, reverse=True) for source, count in aggregated_sources: print source, count try: import matplotlib.pyplot as plt except ImportError: logger.warn('Cannot import matplotlib, skipping chart') return count = sum(c for s, c in aggregated_sources) display_sources = filter(lambda (s, v): float(v) / count >= 0.01, aggregated_sources) sources, values = map(list, zip(*display_sources)) sources.append('Rest') values.append(count - sum(values)) plt.pie(values, labels=sources) plt.axis('equal') plt.show()
def display_result(data_dict, confidence, username): if confidence < 0.4: return plt.figure(figsize=(9, 9)) labels = ['family', 'sport', 'animal', 'art', 'technology', 'life', 'fashion', 'food', 'travel'] colors = ['green', 'blue', 'cyan', 'purple', 'orange', 'pink', 'seagreen', 'red', 'yellow'] sizes = list() explode_list = list() max_label = '' current_value = 0 total_value = 0 for label in labels: sizes.append(data_dict[label]) total_value += data_dict[label] if data_dict[label] > current_value: current_value = data_dict[label] max_label = label for label in labels: if label == max_label: explode_list.append(0.1) else: explode_list.append(0) final_sizes = list() if total_value == 0: return for size in sizes: final_sizes.append(size / total_value) explode = tuple(explode_list) patches, l_text, p_text = plt.pie(final_sizes, explode=explode, labels=labels, colors=colors, autopct='%3.1f%%', shadow=False, startangle=90, pctdistance=0.7) for t in l_text: t.set_size = 12 for t in p_text: t.set_size = 4 plt.axis('equal') user_influence = round(get_user_influence_power(username), 2) plt.text(-1.2, 1.2, 'username: ' + username, fontsize=15) plt.text(-1.2, 1.1, 'confidence: %.2f%%' % (confidence * 100), fontsize=15) plt.text(-1.2, 1, 'social influence: ' + str(user_influence), fontsize=15) file_name = 'user_analysis_result/' + username + '_analysis.png' plt.savefig(file_name, format='png') # This function combine our own dictionary into the overall dictionary such that some special words # can be recognised by the function.