def Statistics(cellnums, resultfile): """ Get the statistics of the each cell type and draw the pie chart """ cells = {"ram": 0, "rod": 0, "hyp": 0, "dys": 0, "amoe": 0} for i in cells.keys(): for j in range(100): cells[i] += cellnums[j][i] colors = ['green', 'blue', 'yellow', 'cyan', 'red'] Allcells = cells['ram'] + cells['hyp'] + cells['dys'] + cells[ 'amoe'] + cells['rod'] sizes = np.asarray([ cells['ram'], cells['hyp'], cells['dys'], cells['amoe'], cells['rod'] ]) / Allcells plt.figure(figsize=(3, 3)) plt.pie(sizes, autopct='%1.1f%%',colors=colors,\ shadow=True, startangle=90) plt.savefig("Pie.png") f = open(resultfile, 'w') f.write('%4s\t%4s\t%4s\t%4s\t%4s\n' % ("ram", "rod", "hyp", "dys", "amoe")) f.write('%4d\t%4d\t%4d\t%4d\t%4d\n' % (cells["ram"],cells["rod"],\ cells["hyp"],cells["dys"],cells["amoe"])) f.close()
def data_visualization2(): #subprocess.check_output(['dos2unix', 'teste.txt']) hamb = [] #subprocess.check_output(['dos2unix', 'write.fasta'], cwd='/home/livanski/Documents/danielsundfeld-hpc/seqs') #with open("teste.txt") as file: with open( '/home/ubuntu/ferramenta_final/servidor_apresentacao/ferramenta/media/arquivo.fasta' ) as file: for line in file: hamb.append(line) seq1 = Seq(hamb[1]) seq2 = Seq(hamb[3]) seq3 = seq1 + seq2 gc = GC(seq3) au = 100 - gc pylab.pie([gc, au]) # cria o grafico pizza pylab.title('GC Content') # indica um titulo pylab.xlabel('GC: %0.1f\nAT: %01.f' % (gc, au)) # porcentagens/info # exibe #pylab.savefig('/home/livanski/Pictures/graph.png', dpi=100) #pylab.savefig('/home/livanski/Music/upload_final/django-upload-example/static/graph.png', dpi=100) pylab.savefig( '/home/ubuntu/ferramenta_final/servidor_apresentacao/ferramenta/mysite/static/css/graph_upload.png', dpi=100) return pylab.show
def save_plt(self): x = [ len(self.plt_1), len(self.plt_2), len(self.plt_3), len(self.plt_4) ] plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.pie( x, labels=['1-5K', '5-8K', '8-15K', '15K-20K'], labeldistance=1.2, # 设置标签距离圆心的距离(0为 圆饼中心数 1为圆饼边缘) autopct="%1.1f%%", # 1.1f% 保留一位小数的百分比 pctdistance=0.5, # 比例值文字距离圆心的距离 explode=[0, 0.2, 0, 0], # 每一块顶点距圆形的长度 colors=["lightskyblue", "green", "royalblue", "magenta"], # 最好一一对应 shadow=True, # 是否有阴影 startangle=60, # 第一块开始的角度 ) plt.axis('equal') # 该行代码使饼图长宽相等 # plt.legend(loc="upper right", fontsize=10, bbox_to_anchor=(1.1, 1.05), borderaxespad=0.3) # plt.loc = 'upper right' # 位于右上角 # plt.bbox_to_anchor=[0.5, 0.5] # 外边距 上边 右边 # plt.ncol=2 # 分两列 # plt.borderaxespad = 0.3 # 图例的内边距 # plt.title("上海市{}岗位薪资占比".format(self.key)) # plt.title("Python Min") # plt.savefig('Python_Min') plt.title("Python Max") plt.savefig('Python_Max') plt.show()
def plot_tipo_tweet(self, archivo_imagen = ''): """ Esta función toma como entrada el archivo de datos preprocesados y devuelve una imagen tipo diagrama de Venn con el tipo de tweets pescados """ #Levantar los datos preprocesados del archivo originales = set(self.tweets.tw_id.values) #Conjunto de tweets originales rt = set(self.tweets[self.tweets.relacion_nuevo_original == 'RT'].or_id.values) #Conjunto de retweets citas = set(self.tweets[self.tweets.relacion_nuevo_original == 'QT'].or_id.values) #Conjunto de citas total_tweets = len(originales.union(rt).union(citas)) #Cantidad total de tweets # Realizar la figura labels = ['RT', 'Originales', 'QT'] sizes = [100 * len(rt) / total_tweets, 100 * len(originales) / total_tweets, 100 * len(citas) / total_tweets] sbn.set_context("paper", font_scale = 1.5) plt.figure(figsize = (11,8), dpi = 300) plt.title('Tipos de Tweets', fontsize = 20) plt.pie(sizes, autopct='%1.1f%%') plt.legend(labels) plt.axis('equal') plt.text(-.1,-1.2,'El total de tweets registrados durante el período fue de : {}'.format(total_tweets)) if archivo_imagen=='': plt.show() else: plt.savefig(archivo_imagen,bbox_inches='tight') plt.show() plt.clf() sbn.reset_orig()
def ZipByDemoCuisine(askNum ,Zipcodes, recorddict): for zips in Zipcodes: if askNum == zips.Zip: print "This is located in " + str(zips.Hood) + "!" labels = ['White', 'Black', 'AI', 'Asian', 'NH/PI', 'Other', 'Multiple', 'Hispanic'] sizes = [zips.White, zips.Black, zips.AI_AN, zips.Asian, zips.NHOPI, zips.OthRace, zips.MultRaces, zips.Hispanic] colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'darkblue','pink', 'purple' ] explode = (0, 0, 0, 0, 0, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=140) plt.axis('equal') plt.show() xlist = [] ylist = [] x = Counter(recorddict[askNum]) for i in x.most_common(10): xlist.append(i[0]) ylist.append(int(i[1])) #i[0] = category #i[1] = number of category labels = xlist sizes = ylist colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'darkblue', 'pink', 'white', 'silver', 'purple'] explode = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=140) plt.axis('equal') plt.show()
def pie_plot_important_activities_2018( ): # pie_plot_important_activities_2018(kaggleSurveyDF_2018, schemaSurveyDF_2018 ): responseCountsList = [] responseOptionsTextListAnnotated = [ 'Analyze and understand data', 'Use ML services to improve product or wokflows', 'Build/run data infrastructure', 'Apply ML to new areas and build prototypes', 'Research/advance state of the art in ML', 'Other / None of these activities are important to my role' ] responseCountsList = [9532, 5481, 5233, 7233, 4934, 4663] plt.figure() plt.pie(x=responseCountsList, labels=responseOptionsTextListAnnotated, startangle=90, autopct='%1.1f%%', wedgeprops={ 'linewidth': 1, 'edgecolor': 'white' }, colors=np.array(plt.get_cmap('tab20').colors)) plt.title( 'What activities make up an important part of your role at work?') plt.show()
def score(self): print('Caculating Your Activity Score.....') colors = ['#ff3300', '#33cc33'] scoreValue = round( math.log((len(urls) + len(searchClean * 2) + len(allLikes * 3) + len(allLinks * 4)) / 9, 1.12), 1) x_0 = [1, 0, 0, 0] pl.pie([100 - scoreValue, scoreValue], autopct='%1.1f%%', startangle=90, colors=colors, pctdistance=10) plt.pie(x_0, radius=0.7, colors='w') plt.axis('equal') plt.title("Your YouTube Activity Score", fontsize=21, color='steelblue', fontweight="bold", fontname="Comic Sans MS") plt.annotate(scoreValue, (0, 0), (115, 154), fontsize=54, color='teal', fontweight="bold", fontname="Comic Sans MS", xycoords='axes fraction', textcoords='offset points', va='top') plt.savefig(image_dir + 'score.png', dpi=400) plt.clf()
def piechart(data,labels,title=0): fig = plt.figure(figsize=(8,8)) plt.pie(data,labels=labels, autopct='%1.1f%%', colors=colors(len(data)), shadow=True) if(title): plt.title(title) return fig
def pie_plot(counts, label, colors, col_name): plt.pie(counts, labels=label, colors=colors, startangle=90, autopct='%.1f%%') plt.savefig(f'../output/graphs/{col_name}_pie_plt.png') plt.show()
def get_region_chart(): count = df['区域'].value_counts() print(count) plt.pie(count, labels=count.keys(), labeldistance=1.4, autopct='%2.1f%%') plt.axis('equal') plt.title('岗位地区分布图') plt.legend(loc='upper left', bbox_to_anchor=(-0.1, 1)) plt.savefig('pie_chart.jpg') plt.show()
def rem_nrem(stages): timespent_array=time_spent_in_stages(stages) time_nrem=timespent_array[1]+timespent_array[2]+timespent_array[3]+timespent_array[4] time_rem=timespent_array[5] split=[(time_rem*100/(time_nrem+time_rem)),(time_nrem*100/(time_nrem+time_rem))] plt.figure() labels=['REM Sleep', 'NREM Sleep'] plt.pie(split,labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) plt.title('Subject 2- Bad Sleep - REM/NREM Splitup') plt.show()
def default_value(self): df = self.df #统计数量,比率 count = df.isnull().sum().sort_values( ascending=False) #统计出每个属性的缺省数量,再根据缺省数量倒排序 ratio = count / len(df) #每个属性的缺省占自己总数的比率 nulldata = pd.concat([count, ratio], axis=1, keys=['count', 'ratio']) #饼状图 explode = [0] explode = explode * len(nulldata.index) explode[0] = 0.1 plt.pie(x=count, labels=nulldata.index, autopct='%1.1f%%', shadow=True, startangle=90, explode=explode, pctdistance=0.8, textprops={ 'fontsize': 16, 'color': 'w' }) #饼状图画出每个属性的缺省在整体缺省数据的占比 plt.title('属性缺省占比图') plt.legend(loc="upper right", bbox_to_anchor=(1.4, 1.1), borderaxespad=0.3) # plt.savefig("picture/default_value_pie.jpg") plt.show() #水平柱状图 plt.figure() plt.barh(nulldata.index, count, 0.5, color='#FFFF00', label="缺省") #每个属性的缺省样本数 plt.barh(nulldata.index, df.shape[0] - count, 0.5, color='#97FFFF', left=count, label="不缺省") #每个属性的样本值不缺省的数量 plt.xlabel("属性") plt.ylabel("样本数") plt.legend() plt.title("每个属性的缺省情况") # plt.savefig("picture/default_value_bar.jpg") plt.show() # 填充缺省,字符串类型的属性用None填充,数值型用众数填充。简单填充,可能会产生更多的误差 for index in nulldata.index: if type(index) is not object: df[index].fillna("None", inplace=True) else: df[index].fillna(df[index].mode()[0], inplace=True) self.df = df return nulldata, df
def badge_bar(index): data1 = pd.read_csv('data/split_class/large_IGNORE_404_badge_+1.txt', sep=' ', header=None) data2 = pd.read_csv('data/split_class/large_IGNORE_404_badge_-1.txt', sep=' ', header=None) col1 = data1[index] col2 = data2[index] print(col1.value_counts() / len(col1)) print(col2.value_counts() / len(col2)) plt.pie(col1.value_counts() / len(col1), colors=('b', 'r'), labels=['badge', 'non-badge']) plt.show()
def DemosForZips(Zipcodes): for zips in Zipcodes: labels = ['White', 'Black', 'AI', 'Asian', 'NH/PI', 'Other', 'Multiple', 'Hispanic'] sizes = [zips.White, zips.Black, zips.AI_AN, zips.Asian, zips.NHOPI, zips.OthRace, zips.MultRaces, zips.Hispanic] colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'blue', 'purple', 'silver'] explode = (0, 0, 0, 0, 0, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=140) plt.axis('equal') plt.show() print zips.Zip + " is located in " + str(zips.Hood) + "!"
def compute_initial_figure(self): UsersPerCountry, UsersPerPlatform = Analytics.UsersPerCountryOrPlatform() labels = [] sizes = [] print(UsersPerPlatform) for p, c in sorted(UsersPerPlatform.iteritems()): labels.append(p) sizes.append(c) colors = ['turquoise', 'yellowgreen', 'firebrick', 'lightsteelblue', 'royalblue'] pylab.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%', shadow=True) pylab.title('Users Per Platform') pylab.gca().set_aspect('1') pylab.show()
def pie_chart(vintage_results, year=40): ''' plot a pie chart show the release break down (by market) for the specific year ''' labels = vintage_results.keys() size = [] explode = (0,0.1,0,0,0,0,0) # only explode the second one colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] for each_key, each_val in vintage_results.iteritems(): this_tot_rel_year = each_val['In Use'][40] + each_val['End of Life'][40] size.append(this_tot_rel_year) plt.pie(size,explode=explode,labels=labels,autopct='%1.1f%%',colors=colors,shadow=True) plt.show()
def score(self): print("Caculating Your Activity Score.....") colors = ["#ff3300", "#33cc33"] score_value = round( math.log( ( len(urls) + len(search_clean * 2) + len(all_likes * 3) + len(all_links * 4) ) / 9, 1.12, ), 1, ) x_0 = [1, 0, 0, 0] pl.pie( [100 - score_value, score_value], autopct="%1.1f%%", startangle=90, colors=colors, pctdistance=10, ) plt.pie(x_0, radius=0.7, colors="w") plt.axis("equal") plt.title( "Your YouTube Activity Score", fontsize=21, color="steelblue", fontweight="bold", fontname="Arial", ) plt.annotate( score_value, (0, 0), (123, 154), fontsize=54, color="teal", fontweight="bold", fontname="Arial", xycoords="axes fraction", textcoords="offset points", va="top", ) plt.savefig(image_dir + "score.png", dpi=400) plt.clf()
def genPiePlot(x,y,fname): colors = ['yellowgreen', 'red', 'gold', 'lightskyblue', 'white', 'lightcoral', 'blue', 'pink', 'darkgreen', 'yellow', 'grey', 'violet', 'magenta', 'cyan'] patches, texts = plt.pie(y, colors=colors, startangle=90, radius=1.2) labels = [] for _x,_y in zip(x,y): labels.append(str(_x) + ' - ' + str(_y)) sort_legend = False if sort_legend: patches, labels, dummy = zip(*sorted(zip(patches, labels, y), key=lambda x: x[2], reverse=True)) #plt.legend(patches, labels, loc='lower center', bbox_to_anchor=(0, .5), # fontsize=12) fig = matplotlib.pyplot.gcf() fig.set_size_inches(18.5, 18.5) plt.savefig(fname, bbox_inches='tight', dpi=100) plt.clf() plt.legend(patches, x, fontsize=23, ncol=3, bbox_to_anchor=(1.,1.)) fig = matplotlib.pyplot.gcf() fig.set_size_inches(18.5, 10.5) fig.savefig(fname + "legend.png", dpi=100) plt.close()
def pie(self, key_word_sep=" ", title=None, **kwargs): """Generates a pylab pie chart from the result set. ``matplotlib`` must be installed, and in an IPython Notebook, inlining must be on:: %%matplotlib inline Values (pie slice sizes) are taken from the rightmost column (numerical values required). All other columns are used to label the pie slices. Parameters ---------- key_word_sep: string used to separate column values from each other in pie labels title: Plot title, defaults to name of value column Any additional keyword arguments will be passsed through to ``matplotlib.pylab.pie``. """ self.guess_pie_columns(xlabel_sep=key_word_sep) import matplotlib.pylab as plt pie = plt.pie(self.ys[0], labels=self.xlabels, **kwargs) plt.title(title or self.ys[0].name) return pie
def getGenderImage(self): for i in range(2): tBD = self.getDurationBookData(i) plotName = "Gender" if i == 0: plotName += " (Short " else: plotName += " (Long " plotName += "BestSeller)" gender = [0,0] # F,M label = ['Female','Male'] for book in tBD: if book[10] == 'F': gender[0] += 1 elif book[10] == 'M': gender[1] += 1 tempColors = self.colors[:2] plt.title(plotName,fontdict={'fontsize':30}) a,b,c=plt.pie(gender, colors = tempColors, labels = label, autopct='%1.1f%%', startangle=90) for text in b: text.set_fontsize(20) plt.axis('equal') plt.show()
def getFirstBSImage(self): for i in range(2): tBD = self.getDurationBookData(i) plotName = "isFirstBestseller" if i == 0: plotName += " (Short " else: plotName += " (Long " plotName += "BestSeller)" isFBS = [0,0] # F,N label = ['First','not First'] for book in tBD: if book[11] == '1': isFBS[0] += 1 elif book[11] == '0': isFBS[1] += 1 tempColors = self.colors[:2] plt.title(plotName,fontdict={'fontsize':30}) a,b,c=plt.pie(isFBS, colors = tempColors, labels = label, autopct='%1.1f%%', startangle=90) for text in b: text.set_fontsize(20) plt.axis('equal') plt.show()
def create_piecharts(grade, total_students, met_students, min_threshold, max_threshold): for major, total in total_students.items(): # 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 = 'Met threshold', 'Did not meet threshold' fracs = [met_students[major]/total, (total-met_students[major])/total] # Pop the slice of the pie out for emphasis explode=(0.1, 0) pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) title('%s Students Between %s-%s for Assignment %s' % (major, min_threshold, max_threshold, grade), bbox={'facecolor':'0.8', 'pad':5}) # Save the figure as a png savefig("piechart_%s_%s_%s-%s.png" % (grade, major, min_threshold, max_threshold), bbox_inches="tight") clf()
def dataDistribution(self): print('Distribuição dos Dados') objects = np.zeros(self._NUM_CLASSES) for i in range(0,self.output_train.shape[0]): out = np.argmax(self.output_train[i]) objects[out] += 1 fig=plt.figure(figsize=(10,5)) fig.add_subplot(1, 2, 1) for i in range(0,self._NUM_CLASSES): plt.bar(i, objects[i], 0.8) plt.xlabel('Classes') plt.ylabel('Elementos') fig.add_subplot(1, 2, 2) for i in range(0,self._NUM_CLASSES): plt.pie(objects ) plt.xlabel('Classes x Elementos') plt.show()
def pie_chart(vintage_results, year=40): ''' plot a pie chart show the release break down (by market) for the specific year ''' labels = vintage_results.keys() size = [] explode = (0, 0.1, 0, 0, 0, 0, 0) # only explode the second one colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] for each_key, each_val in vintage_results.iteritems(): this_tot_rel_year = each_val['In Use'][40] + each_val['End of Life'][40] size.append(this_tot_rel_year) plt.pie(size, explode=explode, labels=labels, autopct='%1.1f%%', colors=colors, shadow=True) plt.show()
def default_value(self): df = self.df #统计数量,比率 count = df.isnull().sum().sort_values( ascending=False) #统计出每个属性的缺省数量,再根据缺省数量倒排序 ratio = count / len(df) #每个属性的缺省占自己总数的比率 nulldata = pd.concat([count, ratio], axis=1, keys=['count', 'ratio']) #饼状图 explode = [0] explode = explode * len(nulldata.index) explode[0] = 0.1 plt.figure() plt.pie(x=count, labels=nulldata.index, autopct='%1.1f%%', shadow=True, startangle=90, explode=explode, pctdistance=0.8, textprops={ 'fontsize': 16, 'color': 'w' }) #饼状图画出每个属性的缺省在整体缺省数据的占比 plt.title('属性缺省占比图') plt.legend(loc="upper right", bbox_to_anchor=(1.4, 1.1), borderaxespad=0.3) if self.port == 11111: plt.savefig("default_value_pie1.jpg") elif self.port == 22222: plt.savefig("default_value_pie2.jpg") elif self.port == 33333: plt.savefig("default_value_pie3.jpg") elif self.port == 44444: plt.savefig("default_value_pie4.jpg") # 填充缺省,字符串类型的属性用None填充,数值型用众数填充。简单填充,可能会产生更多的误差 for index in nulldata.index: if type(index) is not object: df[index].fillna("None", inplace=True) else: df[index].fillna(df[index].mode()[0], inplace=True) return nulldata, df
def pie_chart(all_credit, graph_title): """Display the all_credit dictionary as a pie chart with matplotlib.""" if not ENABLED: return # magic numbers are magical. at least the user can resize afterwards pylab.figure(1, figsize=(6, 6)) pylab.axes([0.1, 0.1, 0.8, 0.8]) pylab.pie( all_credit.values(), labels=all_credit.keys(), autopct='%1.1f%%', shadow=True, startangle=90, ) pylab.title(graph_title) pylab.show()
def percentTimeIn(): """ Funcao que retorna o percentual de tempo em cada intervalo informado. """ if len(ds.EpmDatasetAnalysisPens.SelectedPens) != 1: sr.msgBox('EPM Python Plugin - Demo Tools', 'Please select a single pen before applying this function!', 'Warning') return 0 epmData = ds.EpmDatasetAnalysisPens.SelectedPens[0].values global nodes runDialogInterval() global nodes t, y = rmNanAndOutliers2(epmData) if len(nodes) < 2: minVal = int(np.floor(np.nanmin(y))) maxVal = int(np.ceil(np.nanmax(y))) step = int((maxVal - minVal) / 3) nodes = range(minVal, maxVal, step) intervNum = np.size(nodes) + 1 totTime = np.empty(intervNum, dtype=object) totTime.fill(dtt.timedelta(0, 0)) for i in range(1, np.size(y)): dt = t[i] - t[i - 1] ix = np.digitize([y[i]], nodes) totTime[ix] += dt nodesPercents = np.zeros([np.size(totTime), 2]) totalPeriod = totTime.sum().total_seconds() for i in range(np.size(totTime)): if i: nodesPercents[i, 0] = nodes[i - 1] else: nodesPercents[i, 0] = -np.inf nodesPercents[i, 1] = totTime[i].total_seconds() / totalPeriod labels = [] for item in nodesPercents[:, 0]: labels.append(str(item)) pl.pie(nodesPercents[:, 1], labels=labels, autopct='%1.1f%%', shadow=True) pl.show() return nodesPercents
def percentTimeIn(): """ Funcao que retorna o percentual de tempo em cada intervalo informado. """ if len(ds.EpmDatasetAnalysisPens.SelectedPens) != 1: sr.msgBox('EPM Python Plugin - Demo Tools', 'Please select a single pen before applying this function!', 'Warning') return 0 epmData = ds.EpmDatasetAnalysisPens.SelectedPens[0].values global nodes runDialogInterval() global nodes t,y = rmNanAndOutliers2(epmData) if len(nodes) < 2: minVal = int(np.floor(np.nanmin(y))) maxVal = int(np.ceil(np.nanmax(y))) step = int((maxVal-minVal)/3) nodes = range(minVal,maxVal,step) intervNum = np.size(nodes)+1 totTime = np.empty(intervNum, dtype=object) totTime.fill(dtt.timedelta(0,0)) for i in range(1,np.size(y)): dt = t[i] - t[i-1] ix = np.digitize([y[i]], nodes) totTime[ix] += dt nodesPercents = np.zeros([np.size(totTime),2]) totalPeriod = totTime.sum().total_seconds() for i in range(np.size(totTime)): if i: nodesPercents[i,0] = nodes[i-1] else: nodesPercents[i,0] = -np.inf nodesPercents[i,1] = totTime[i].total_seconds()/totalPeriod labels = [] for item in nodesPercents[:,0]: labels.append(str(item)) pl.pie(nodesPercents[:,1], labels=labels, autopct='%1.1f%%', shadow=True) pl.show() return nodesPercents
def responses_pieplot(): response_data = pd.read_csv('response_percents.csv') #response_data = pd.read_csv('response_percents_reordered.csv') #print (response_data) fig, ax = plt.subplots(figsize=(7, 7)) explode = [0, 0, 0, 0, 0, 0, 0.1] labels = response_data['Hall'] #labels_gender = response_data['Gender'] colors = [ '#ffad30', '#c369ff', '#2ff59c', '#b5b5b5', '#ff4063', '#4dbeff', '#ff69b6' ] colors_gender = ['#2081C3', '#ff6969'] plt.pie(x=response_data['Percent'], explode=explode, labels=labels, colors=colors, labeldistance=1.05, autopct='%.1f%%', pctdistance=0.64) #plt.pie(x=response_data['Percent'], labels=labels_gender, colors=colors_gender, labeldistance=0.5, autopct='%.1f%%', pctdistance=0.6) plt.legend(frameon=False) plt.show()
def getPublishYearImage(self,labelNum): for durationNum in range(2): plotName = "BSYear - PublishedYear" if durationNum == 0: plotName += " (Short " else: plotName += " (Long " plotName += "BestSeller)" tBD = self.getDurationBookData(durationNum) yearDict = {} for book in tBD: bsYear = int(book[0]) pYear = int(book[4]) difYear = bsYear - pYear if difYear in yearDict: yearDict[difYear] += 1 else: yearDict[difYear] = 1 yearNumList = [] for year in yearDict: yearNumList.append((year,yearDict[year])) yearNumList.sort(reverse = True, key = lambda year: year[0]) print(yearNumList) if labelNum < len(yearNumList): etcNum = 0 for i in range(labelNum,len(yearNumList)): etcNum += yearNumList[i][1] yearNumList = yearNumList[0:labelNum] yearNumList.append(('etc',etcNum)) yearList = [] numList = [] for i in range(len(yearNumList)): yearList.append(yearNumList[i][0]) numList.append(yearNumList[i][1]) tempColors = self.colors[:len(numList)] plt.title(plotName,fontdict={'fontsize':30}) a,b,c=plt.pie(numList, colors = tempColors, labels = yearList, autopct='%1.1f%%', startangle=90) for text in b: text.set_fontsize(20) plt.axis('equal') plt.show()
def getSpecificGenreImage(self): genreColorDict = {} for i in range(20): genreColorDict[i] = self.colors[i] for genreNum in [2,3,6]: tBD = self.getDurationBookData(2) referenceDict = {} for i in range(5): referenceDict[i] = 0 for book in tBD: if int(book[2]) == genreNum: reference = int(book[9])+int(book[10]) if reference > 3: referenceDict[4] += 1 else: referenceDict[reference] += 1 genreDict = referenceDict genreNumList = [] for genre in genreDict: genreNumList.append((genre,genreDict[genre])) genreNumList.sort(key = lambda genre: genre[0]) genreList = [] numList = [] tempColors = [] for i in range(len(genreNumList)): print(genreNumList[i]) if genreNumList[i][0] == 4: genreList.append(">3") else: genreList.append(genreNumList[i][0]) numList.append(genreNumList[i][1]) tempColors.append(genreColorDict[genreNumList[i][0]]) #plt.title(plotName,fontdict={'fontsize':20}) a,b,c = a,b,c=plt.pie(numList, colors = tempColors, labels = genreList, autopct='%1.1f%%', startangle=90) for text in b: text.set_fontsize(20) plt.axis('equal') plt.show()
def pie(self, sizes): labels = ['Var_Credit(Closing)', 'Var_Interest(Closing)'] #print(sizes) abc = [float(x) * -1 for x in sizes] colors = ['lightsage', 'crimson'] #patches, texts = plt.pie(abc, colors=colors, startangle=90) #plt.legend(patches, labels, loc="best") plt.axis('equal') plt.tight_layout() plt.title("VaR Distribution for Closing Book") explode = (0, 0.1) pie = plt.pie(abc, colors=colors, labels=labels, explode=explode, shadow=True, autopct='%1.3f%%') plt.legend(pie[0], labels, loc="best") plt.show()
def getPublisherImage(self,labelNum): for durationNum in range(2): plotName = "Genre" if durationNum == 0: plotName += " (Short " else: plotName += " (Long " plotName += "BestSeller)" tBD = self.getDurationBookData(durationNum) genreDict = {} for book in tBD: genre = book[5] if genre in genreDict: genreDict[genre] += 1 else: genreDict[genre] = 1 genreNumList = [] for genre in genreDict: genreNumList.append((genre,genreDict[genre])) genreNumList.sort(reverse = True, key = lambda genre: genre[1]) print(genreNumList) if labelNum < len(genreNumList): etcNum = 0 for i in range(labelNum,len(genreNumList)): etcNum += genreNumList[i][1] genreNumList = genreNumList[0:labelNum] genreNumList.append(('etc',etcNum)) genreList = [] numList = [] for i in range(len(genreNumList)): genreList.append(genreNumList[i][0]) numList.append(genreNumList[i][1]) tempColors = self.colors[:len(numList)] plt.title(plotName,fontdict={'fontsize':30}) a,b,c=plt.pie(numList, colors = tempColors, labels = genreList, autopct='%1.1f%%', startangle=90) for text in b: text.set_fontsize(20) plt.axis('equal') plt.show()
def getGenreImage(self): genreColorDict = {} for i in range(10): genreColorDict[i] = self.colors[i] for durationNum in range(3): plotName = "Genre" if durationNum == 0: plotName += " (Short " else: plotName += " (Long " plotName += "BestSeller)" tBD = self.getDurationBookData(durationNum) genreDict = {} for i in range(10): genreDict[i] = 0 i = 0 for book in tBD: genre = book[2] genreDict[int(genre)] += 1 genreNumList = [] for genre in genreDict: genreNumList.append((genre,genreDict[genre])) genreNumList.sort(reverse = True, key = lambda genre: genre[1]) genreList = [] numList = [] tempColors = [] for i in range(8): genreList.append(self.genreNumToName[genreNumList[i][0]]) numList.append(genreNumList[i][1]) tempColors.append(genreColorDict[genreNumList[i][0]]) # plt.title(plotName,fontdict={'fontsize':30}) a,b,c = a,b,c=plt.pie(numList, colors = tempColors, labels = genreList, autopct='%1.1f%%', startangle=90) for text in b: text.set_fontsize(30) plt.axis('equal') plt.show()
def getReferenceByImage(self): tempRefList = [] for i in range(2): bD = self.getDurationBookData(i) for book in bD: if book[1] == 'Literature&Fiction': tempRefList.append((book[1],int(book[8])+int(book[9]),int(book[12]))) tempRefList.sort(reverse = True, key = lambda genre: genre[1]) refDict = {} for book in tempRefList: if book[1] in refDict: refDict[book[1]] += 1 else: refDict[book[1]] = 1 temp = [] for ref in refDict: temp.append((ref,refDict[ref])) temp.sort(key = lambda genre: genre[0]) genreList = [] numList = [] tempColors = [] for i in range(len(temp)): genreList.append(temp[i][0]) numList.append(temp[i][1]) tempColors = self.colors[:len(numList)] numList[6] = sum(numList[6:]) numList = numList[:7] genreList = genreList[:6] genreList.append('etc') tempColors = self.colors[:len(genreList)] a,b,c=plt.pie(numList, colors = tempColors, labels = genreList, autopct='%1.1f%%', startangle=90) for text in b: text.set_fontsize(20) plt.axis('equal') plt.show()
for s in page_grouped: n = max(s) n = n + (10 - n % 10) dic[n] = len(s) return dic dic = getPageSorted(files) print('le nombre de page pour chaque pdf') print(dic) dic = getGroupedPage(dic) print("nombre de page regrouper") print(dic) dic = getRegroupedPage(dic) print("regrouped pages ") print(dic) plt.subplots(figsize=(20, 10)) lists = sorted(dic.items()) # sorted by key, return a list of tuples plt.pie([float(v) for v in dic.values()], autopct='%2.2f%%', shadow=True, startangle=140) plt.legend(labels=["page< " + str(k) + " " + str(dic[k]) for k in dic], bbox_transform=plt.gcf().transFigure, fontsize=30, loc="best") plt.axis('equal') plt.show()
def checkmem(origvariable, descend=0, order='n', plot=False, verbose=0): """ Checks how much memory the variable in question uses by dumping it to file. Example: from utils import checkmem checkmem(['spiffy',rand(2483,589)],descend=1) """ from os import getcwd, remove from os.path import getsize from cPickle import dump from numpy import iterable, argsort filename = getcwd()+'/checkmem.tmp' def dumpfile(variable): wfid = open(filename,'wb') dump(variable, wfid) return None printnames = [] printbytes = [] printsizes = [] varnames = [] variables = [] if descend==False or not(iterable(origvariable)): varnames = [''] variables = [origvariable] elif descend==1 and iterable(origvariable): if hasattr(origvariable,'keys'): for key in origvariable.keys(): varnames.append(key) variables.append(origvariable[key]) else: varnames = range(len(origvariable)) variables = origvariable for v,variable in enumerate(variables): if verbose: print('Processing variable %i of %i' % (v+1, len(variables))) dumpfile(variable) filesize = getsize(filename) factor = 1 label = 'B' labels = ['KB','MB','GB'] for i,f in enumerate([3,6,9]): if filesize>10**f: factor = 10**f label = labels[i] printnames.append(varnames[v]) printbytes.append(filesize) printsizes.append('%0.3f %s' % (float(filesize/float(factor)), label)) remove(filename) if order=='a' or order=='alpha' or order=='alphabetical': inds = argsort(printnames) else: inds = argsort(printbytes) for v in inds: print('Variable %s is %s' % (printnames[v], printsizes[v])) if plot==True: from matplotlib.pylab import pie, array, axes axes(aspect=1) pie(array(printbytes)[inds], labels=array(printnames)[inds], autopct='%0.2f') return None
# 各组销量的总计之和 sizeTotal = size1Count.sum() # 吧series转换为dataFrame类型 size1 = size1Count.to_frame(name="销量") # print(size) # print(type(size)) # 插入比例 scal = 100.0 * size1Count / sizeTotal # print(scal) # 设置格式化输出 pandas.options.display.float_format = "{:,.2f}%".format # 插入比例 size1.insert(0, "比例", scal) # 修改索引名称 size1.index.names = ['罩杯'] # 打印结果 print(size1) # 设置标签 lables1 = ["A", "B", "C"] lables2 = ["A", "B", "C"] sales_num = size1['销量'] # 绘制病状第一个参数是数据,第二个参数是数据的一个格式化,第三个参数是标签 plb.pie(sales_num, autopct="%.2f%%", labels=lables1) # 设置圆形并且均匀 plb.axis('equal') # 设置图的标题 plb.title("罩杯销售量", FontProperties=font) # 设置示例 plb.legend(lables2) plb.show()
import matplotlib.pylab as plt # graphic을 위한 모듈 from matplotlib import rc rc('font', family="Malgun Gothic") # 한글 가능한 폰트 설정 labels = ['개구리', '돼지', '개', '통나무'] # 이름 sizes = [15, 30, 45, 10] # 데이터 colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = (0, 0.1, 0, 0) # 중심에서 간격 수치로 지정 plt.title("Pie Chart") # wedgeprops : 부채꼴 설정 # width : 반지름 대비 비율 # linewidth : 구분선 굵기 wedgeprops = {'width': 0.7, 'edgecolor': 'w', 'linewidth': 2} #그래프 작성 # autopct : 부채꼴 내부에 표시되는 내용의 형식. # startangle : 시작되는 위치 각도 지정. 배치순서 반시계 방향. plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, wedgeprops=wedgeprops) plt.show()
[106.7882176183174, 51.407011395593209, 344.10490569403436, 322.25600000000003, 106.7882176183174, 410.40199893791083, 5.7000277630265392]] #weight fraction pie chart the_grid = GridSpec(2, 3) for i in range(3): M_fuse_empty = data[i]['fuse_weight.M_tot'] - data[i]['fuse_weight.M_pilots'] M_empty = data[i]['wing_weight.M_tot'] + M_fuse_empty ax = plt.subplot(the_grid[0, i], aspect=1) estimated_masses = np.array([data[i]['wing_weight.M_tot'], M_fuse_empty, M_fuse_empty-2.512*(i+1)-3.499*(i+1)])/M_empty labels = ['wing','pod','control surf.'] #print M_empty, estimated_masses #print data[i]['wing_weight.s'] plt.pie(estimated_masses, labels=labels, autopct='%.0f%%',) ax.set_title('%d Pilot'%(i+1)) plt.tight_layout() plt.savefig('pilot_study_pie.pdf') #total power req plt.figure() fig, ax = plt.subplots() raw_data = np.array(cantilever_data) ax.plot([1,2,3,4], raw_data[:,5],label="cantilever") raw_data = np.array(two_wire_data) ax.plot([1,2,3,4], raw_data[:,5],label="two-wire") ax.legend(loc="best")
grouped = df.groupby('Expenditure Account Code Description') total = grouped.sum().sort_values('Amount',ascending=False) # Pie chart grouped = df[~df['Directorate'].isnull()].groupby('Directorate') total = grouped.sum().sort_values('Amount',ascending=False) plt.figure(figsize=(7,4)) labels = total.index.values labels[5:] = '' cmap = plt.cm.jet colors = cmap(np.linspace(0., 2., len(total))) explode = tuple(np.linspace(0,0.8,len(total))) patches, texts = plt.pie(total['Amount'], radius=0.9, startangle=0, colors=colors,explode=explode,labels=labels) _ = [texts[i].set_fontsize(10) for i in range(0,len(total))] plt.axis('equal') plt.title('Total Spendings (2013-2016)') plt.tight_layout() #plt.legend(labels=labels, loc="best",fontsize=9,bbox_to_anchor=(0.43, 0.6))
plt.plot(data1,data3) #Plot scatter plt.cla() plt.scatter(carDf.PRICE, carDf.WEIGHT, color='r') #Plot bar charts plt.cla() plt.bar(carDf.ID, carDf.PRICE) plt.cla() plt.barh(carDf.ID, carDf.WEIGHT) plt.yticks(carDf.ID, carDf.MODEL) #Plot pie chart plt.cla() plt.pie(carDf.PRICE, labels=carDf.MODEL, shadow=True, autopct='%1.1f') #Plot a histogram plt.cla() plt.hist(data3, color='g') plt.title('Demo Histogram') plt.xlabel('Sin Weights') plt.ylabel('Frequency') #Plot a boxplot plt.cla() #pass a list of lists plt.boxplot([[carDf.WEIGHT[carDf.MAKE=='Toyota']], [carDf.WEIGHT[carDf.MAKE=='Ford']] ], labels=('Toyota','Ford')) #show show weights change by make of car
canvas1 = FigureCanvasTkAgg(f, master=tab4) canvas1.show() #Create the FIRST plot tartita=figure(1, figsize=(3,3),facecolor="white") ax = axes([0.1, 0.1, 0.8, 0.8]) # The slices will be ordered and plotted counter-clockwise. labels = 'Cash', 'Credit Card' pieChartData = pos.generateCCReport() fracs = [pieChartData[0], pieChartData[1]] explode=(0, 0.1) pie(fracs, explode=explode, labels=labels, autopct=pos.make_autopct(pieChartData), shadow=True, startangle=90, colors= ["#E13F29", "#D69A80"]) canvas = FigureCanvasTkAgg(tartita, master=tab4) canvas.show() #Create the third plot linechartita=figure(3, figsize=(3,3),facecolor="white") # x axis lineChartData = pos.getLastDaysSales() lineChartdays = lineChartData[0] # y axis lineChartSales = lineChartData[1] plot(lineChartdays, lineChartSales) xlabel('Days')
def findSimilarZip(askZip, ziplist, recorddict, Zipcodes): xlist = [] ylist = [] ZipList = [] x = Counter(recorddict[askZip]) for i in x.most_common(12): xlist.append(i[0]) ylist.append(int(i[1])) myZip = xlist[0:4] nyZip = ylist[0:4] labels = xlist sizes = ylist colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'blue', 'purple', 'white', 'silver', 'pink', 'lightsalmon', 'lightsage'] explode = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.2f%%', shadow=False, startangle=140) plt.axis('equal') plt.show() for zips in Zipcodes: if askZip == zips.Zip: print "This is located in " + str(zips.Hood) + "!" labels = ['White', 'Black', 'AI', 'Asian', 'NH/PI', 'Other', 'Multiple', 'Hispanic'] sizes = [zips.White, zips.Black, zips.AI_AN, zips.Asian, zips.NHOPI, zips.OthRace, zips.MultRaces, zips.Hispanic] colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'darkblue','pink', 'purple' ] explode = (0, 0, 0, 0, 0, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=140) plt.axis('equal') plt.show() for Zip in ziplist: z = Counter(recorddict[Zip]) y1 = [] z1 = [] for i in z.most_common(12): y1.append(i[0]) z1.append(i[1]) y2 = y1[0:4] z2 = z1[0:4] if myZip == y2 and askZip != Zip: ZipList.append(Zip) labels = y1 sizes = z1 colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'blue', 'purple', 'white', 'silver', 'pink', 'lightsalmon', 'lightsage'] explode = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.2f%%', shadow=False, startangle=140) plt.axis('equal') plt.show() for zips in Zipcodes: if Zip == zips.Zip: print str(Zip) + " is similar to " + str(askZip) + "." print "This is located in " + str(zips.Hood) + "!" labels = ['White', 'Black', 'AI', 'Asian', 'NH/PI', 'Other', 'Multiple', 'Hispanic'] sizes = [zips.White, zips.Black, zips.AI_AN, zips.Asian, zips.NHOPI, zips.OthRace, zips.MultRaces, zips.Hispanic] colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'darkblue','pink', 'purple' ] explode = (0, 0, 0, 0, 0, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=140) plt.axis('equal') plt.show() else: continue if len(ZipList) == 0: print "This zip code is truly unique!" return ZipList
def first_round_user_query_visualization(df, plot_flag, fig_dir_path): if plot_flag == 'min': title_prefix = "Minimum" else: title_prefix = "Preferred" df3, category, perc = get_degree(df, plot_flag) df4_sorted, color = get_sorted_degree_area(df, plot_flag) df5_sorted = get_sorted_skills(df, plot_flag) #print df5_sorted #df5_sorted = df5_sorted.head(10) # Create 2x2 sub plots pie_colors = [[183, 183, 183], [230, 252, 209], [252, 230, 174], [168, 247, 239], [255, 188, 122], [214, 198, 255], [255, 226, 242]] pie_colors = [[ pie_colors[i][0] / 255.0, pie_colors[i][1] / 255.0, pie_colors[i][2] / 255.0 ] for i in range(len(pie_colors))] gs = gridspec.GridSpec(2, 2) #plot pie chart for degree fig = pl.figure(figsize=(18, 12)) ax = pl.subplot(gs[0, 0]) # row 0, col 0 n = pl.pie(perc, labels=category, colors=pie_colors[:len(category)], startangle=90, autopct='%.1f%%', textprops={'fontsize': small_fontsize}) ax.set_aspect('equal') pl.title(title_prefix + " Qualifications - Degree", fontsize=20, fontweight='bold') # plot bar chart for degree areas ax = pl.subplot(gs[0, 1]) # row 0, col 1 objects = df4_sorted["Degree_Area"] y_pos = np.arange(len(objects)) performance = df4_sorted["Percent"] pl.barh(y_pos, performance, align='center', alpha=0.5, color=tuple(color)) pl.yticks(y_pos, objects, rotation=0, fontsize=small_fontsize) pl.xlabel('Percent %', fontsize=14) pl.xlim([0, 100]) pl.title('Degree Majors', fontsize=20, fontweight='bold') #pl.rcParams.update({'font.size': 8}) ax = pl.subplot(gs[1, :]) # row 1, span all columns df5_sorted = df5_sorted.iloc[:15] df5_sorted = df5_sorted.sort_values(['Count'], ascending=[1]) objects = df5_sorted["Exp/Skills"] y_pos = np.arange(len(objects)) performance = df5_sorted["Percent"] pl.barh(y_pos, performance, align='center', alpha=0.5) pl.yticks(y_pos, objects, rotation=0, fontsize=small_fontsize) pl.xlabel('Percent %', fontsize=14) pl.xlim([0, 30]) pl.title('Top 15 Exp/Skills', fontsize=20, fontweight='bold') pl.show()
def tradeanalyze4(rpt,fname,outputDir,data): """ エグジット要因ごとの勝率 """ print "\n--------------------------------------------" print "- Exit \n" print 'Entry -> Exit : profit rate [win/total]' cc = [] cd = [] count = 1 for t in ['close','t/p','s/l']: f = filter(lambda n:n[6]==t ,rpt.buyorder) cc.append(len(f)) pc,nc = winlossCount(f) if pc+nc>0: t0 = "%6.2f %% [ %3d / %3d ]" % (100*float(pc)/float(pc+nc),pc,\ (pc+nc)) cd.append(100*float(pc)/float(pc+nc)) t1 = "Long - %6s : " % (t) print t1 + t0 t3 = "$$T0040%02d$$" % (count) count = count+1 data.update({t3:t0}) else: t3 = "$$T0040%02d$$" % (count) count = count+1 data.update({t3:'NA'}) cd.append(0.) for t in ['close','t/p','s/l']: f = filter(lambda n:n[6]==t ,rpt.sellorder) cc.append(len(f)) pc,nc = winlossCount(f) if pc+nc>0: t0 = "%6.2f %% [ %3d / %3d ]" % (100*float(pc)/float(pc+nc),pc,\ (pc+nc)) cd.append(100*float(pc)/float(pc+nc)) t1 = "Short- %6s : " % (t) print t1 + t0 t3 = "$$T0040%02d$$" % (count) count = count+1 data.update({t3:t0}) else: t3 = "$$T0040%02d$$" % (count) count = count+1 data.update({t3:'NA'}) cd.append(0.) s = np.array([cd[0],cd[1],cd[2]]) b = np.array([cd[3],cd[4],cd[5]]) x = np.array(range(len(s))) xt = ['close','t/p','s/l'] gw = 0.4 plt.figure(figsize=(5,2)) plt.title('Profit rate by exit ') plt.xlabel("Profit rate") plt.xlim(0,100) #plt.ylim(0+0.5,5-0.5) plt.yticks(x,xt) plt.grid(True) plt.barh(x -gw/2, s, height = gw, align='center',color='b',alpha=0.5,\ label='Short') plt.barh(x +gw/2, b, height = gw, align='center',color='g',alpha=0.5,\ label='Long' ) plt.legend() plt.axvline(50,color='r') plt.savefig(outputDir+fname+"test41.png",dpi=72) data.update({'$$I004001$$':fname+"test41.png"}) #plt.show() plt.draw() ac = cc[0]+cc[3] tc = cc[1]+cc[4] sc = cc[2]+cc[5] tt = ac+tc+sc print " " t0 = "%6.2f %% [ %4d / %4d ]" % (100*float(ac)/float(tt),ac,tt) t1 = "%6.2f %% [ %4d / %4d ]" % (100*float(tc)/float(tt),tc,tt) t2 = "%6.2f %% [ %4d / %4d ]" % (100*float(sc)/float(tt),sc,tt) print "Exit : rate [count/total]" print "Close : " + t0 print "t/p : " + t1 print "s/l : " + t2 data.update({'$$T005001$$':t0}) data.update({'$$T005002$$':t1}) data.update({'$$T005003$$':t2}) from matplotlib import cm plt.figure(figsize=(2,2)) names =[ 'close','t/p', 's/l'] # それぞれの割合を用意 ratios = [ac, tc,sc] # どれだけ飛び出すか指定 moves=(0, 0, 0) # 適当なカラーをマッピング col = cm.Set2(np.arange(3)/3.,0.7) # 円グラフを描画(影付き) plt.pie(ratios, explode=moves, labels=names, autopct='%1d%%',\ shadow=True,colors=col) # 円グラフ他ので縦横比は等しく plt.gca().set_aspect('equal') plt.title('Exit count') plt.savefig(outputDir+fname+"test42.png",dpi=72) data.update({'$$I004002$$':fname+"test42.png"}) #plt.show() plt.draw() plt.close('all')