def compareAnimals(animals,precision): '''假设animals是动物列表, precision是大于等于0的整数,生成一个表格,包含任意两个动物之间的欧氏距离''' #生成表格的行与列 columnLabels=[] for a in animals: columnLabels.append(a.getName()) rowLabels=columnLabels[:] tableVals=[] #计算动物之间的距离 #循环每行 for a1 in animals: row=[] #循环每列 for a2 in animals: if a1==a2: row.append('--') else: distance=a1.distance(a2) row.append(str(round(distance,precision))) tableVals.append(row) #生成表格 table=pylab.table(rowLabels=rowLabels, colLabels=columnLabels, cellText=tableVals, cellLoc='center', loc='center', colWidths=[0.2]*len(animals)) table.scale(1,2.5) pylab.axis('off') #不显示x轴和y轴 pylab.savefig('distances')
def compareAnimals(animals, precision): """Assumes animals is a list of animals, precision an int >= 0 Builds a table of Euclidean distance between each animal""" #Get labels for columns and rows columnLabels = [] for a in animals: columnLabels.append(a.getName()) rowLabels = columnLabels[:] tableVals = [] #Get distances between pairs of animals #For each row for a1 in animals: row = [] #For each column for a2 in animals: if a1 == a2: row.append('--') else: distance = a1.distance(a2) row.append(str(round(distance, precision))) tableVals.append(row) #Produce table table = pylab.table(rowLabels = rowLabels, colLabels = columnLabels, cellText = tableVals, cellLoc = 'center', loc = 'center', colWidths = [0.2]*len(animals)) table.scale(1, 2.5) pylab.axis('off') #Don't display x and y-axes pylab.savefig('distances')
def TablePlot(): index_time=0 # print [x[2] for x in RouteTablewithSeq] pl.ion() fig,ay=pl.subplots() fig,ax=pl.subplots() fig.set_tight_layout(True) idx_row = Index(np.arange(0,nNodes)) idx_col = Index(np.arange(0,nPackets)) df = DataFrame(cache_matrix[0,:,:], index=idx_row, columns=idx_col) # print df normal = pl.Normalize(0, 1) for index_time in range(len(RouteTablewithSeq_time)): vals=cache_matrix[index_time,:,:30] # fig = pl.figure(figsize=(15,8)) # ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[]) # print vals.shape the_table=pl.table(cellText=vals, rowLabels=df.index, colLabels=df.columns, colWidths = [0.03]*vals.shape[1], loc='center', cellColours=pl.cm.hot(normal(vals)), fontsize=3) the_table.alpha=0 for i in range(index_time+1): for j in range(vals.shape[0]): if (vals[j,i]==1): the_table._cells[(j+1, i)]._text.set_color('white') pl.title("Table at time: "+str(cache_time[index_time])+" Packet: "+str(index_time)+" Probability: "+str(p) ) pl.show() pl.pause(.0005) pl.clf()
def PlotWeightTable(self): """ Plots the table of weights """ # # Get the labels and cell text # colLabels, rowLabels, cellText, cellColours = self._GetTableCells( VectSep=', ') rowColours = [] for row in cellColours: rowColours.append(row[0]) colWidths = self._GetTableColWidths(rowLabels, cellText, colLabels) CurrentAxis = pyl.axes([0.07, 0.1, 0.9, 0.9]) CurrentAxis.autoscale_view(tight=False, scalex=True, scaley=False) pyl.axis('off') table = pyl.table(cellText=cellText, cellLoc='center', rowLabels=rowLabels, rowLoc='left', rowColours=rowColours, colLabels=colLabels, colLoc='center', colWidths=colWidths, cellColours=cellColours, loc='upper right')
def compareAnimals(animals, precision): """Assumes animals is a list of animals, precision an int >= 0 Builds a table of Euclidean distance between each animal""" colLables = [] for a in animals: colLables.append(a.getName()) rowLabels = colLables[:] tableVals = [] # get distance between each pair of animals for a1 in animals: row = [] for a2 in animals: if a1 == a2: row.append("--") else: dist = a1.distance(a2) row.append(round(dist, precision)) tableVals.append(row) # produce the table table = pylab.table(rowLabels=rowLabels, colLabels=colLables, cellText=tableVals, cellLoc='center', loc='center', colWidths=[0.2] * len(animals)) table.scale(1, 2.5) pylab.axis('off') pylab.savefig('distances') pylab.show()
def compareAnimals(animals, precision): """Assumes animals is a list of animals, precision an int >= 0 Builds a table of Euclidean distance between each animal""" #Get labels for columns and rows columnLabels = [] for a in animals: columnLabels.append(a.getName()) rowLabels = columnLabels[:] tableVals = [] #Get distances between pairs of animals #For each row for a1 in animals: row = [] #For each column for a2 in animals: if a1 == a2: row.append('--') else: distance = a1.distance(a2) row.append(str(round(distance, precision))) tableVals.append(row) #Produce table table = pylab.table(rowLabels = rowLabels, colLabels = columnLabels, cellText = tableVals, cellLoc = 'center', loc = 'center', colWidths = [0.138]*len(animals)) table.auto_set_font_size(False) table.set_fontsize(10) help(table.scale) table.scale(1, 2.5) pylab.axis('off') pylab.savefig('distances')
def compareAnimals(animals, title, precision, p=2): """ :param p: 闵式距离参数 默认为2,即欧几里得距离 :param animals: list of Animals :param precision: 距离精度 制作一张table,该table绘制了不同动物之间的距离 """ # 1.行列起首的名称 column_label = [] for ani in animals: column_label.append(ani.get_name()) row_label = column_label[:] # 2.计算动物之间的距离 table_val = [] for i in range(len(animals)): ani = animals[i] this_row_val = [] for j in range(len(animals)): if i == j: this_row_val.append("--") else: this_row_val.append( str( round(ani.get_minkowski_dist_from_other(animals[j], p), precision))) table_val.append(this_row_val) # 3.绘制距离图 pylab.figure(num=1, frameon=False) table = pylab.table( rowLabels=row_label, colLabels=column_label, cellText=table_val, cellLoc="center", # 每个cell里面的内容摆放位置 loc="center", # 整个table在figure的摆放位置 colWidths=[0.2] * len(animals), # 每列的宽度 ) table.scale(1, 2.5) # table的cell的宽度不变,高度*2.5 # 去除掉 x轴 和 y轴的刻度 # pylab.xticks(ticks=[]) # pylab.yticks(ticks=[]) # 去掉坐标轴 pylab.axis('off') pylab.title(title) pylab.show()
def generate_table(table_data, rows, columns): df = DataFrame(table_data, index=rows, columns=columns) base = 0 colorings = [] #colorings.append([base]*(len(rows)+1)) for column in columns: vals = df[column].values normal = normalize(vals.min() - 1, vals.max() + 1) m = cm.ScalarMappable( norm=matplotlib.colors.Normalize(vmin=vals.min(), vmax=vals.max())) m.set_cmap("YlGn") col_colors = m.to_rgba(vals) print col_colors colorings.append(col_colors) #colorings.append(list(np.transpose(cm.hot(normal(vals)))[1])) colorings = np.transpose(colorings, (1, 0, 2)) print colorings.shape fig = figure(figsize=(15, 8)) ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[]) #print colorings vals = df.values the_table = table(cellText=vals, rowLabels=df.index, colLabels=df.columns, colWidths=[0.13] * vals.shape[1], loc='center', cellColours=colorings, fontsize=15) #nrows, ncols = len(rows)+1, len(columns)+1 #hcell, wcell = 1, 1 #hpad, wpad = .5, 0 #fig = figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad)) #fig = figure() #ax = fig.add_subplot(111) #ax.axis('off') #ax.table(cellText=table_data, # rowLabels=rows, # colLabels=columns, # loc='center') show() close()
def print_table(self, display=False): title = "HAC Table | " + self.name plt.figure() cells = map(lambda c: [len(c.points)], self.clusters) rows = map(lambda i: "Cluster {0}".format(i), range(1, len(self.clusters)+1)) the_table = plt.table( cellText=cells, colWidths=[0.2], rowLabels=rows, colLabels=["# Instances"], loc="center" ) plt.text(0, 0, title, size=20) plt.savefig(title + ".pdf") if display: plt.show()
def generate_table(table_data,rows,columns): df = DataFrame(table_data, index=rows, columns=columns) base = 0 colorings = [] #colorings.append([base]*(len(rows)+1)) for column in columns: vals = df[column].values normal = normalize(vals.min()-1, vals.max()+1) m = cm.ScalarMappable(norm=matplotlib.colors.Normalize(vmin=vals.min(), vmax=vals.max())) m.set_cmap("YlGn") col_colors = m.to_rgba(vals) print col_colors colorings.append(col_colors) #colorings.append(list(np.transpose(cm.hot(normal(vals)))[1])) colorings = np.transpose(colorings,(1,0,2)) print colorings.shape fig = figure(figsize=(15,8)) ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[]) #print colorings vals = df.values the_table=table(cellText=vals, rowLabels=df.index, colLabels=df.columns, colWidths = [0.13]*vals.shape[1], loc='center', cellColours=colorings, fontsize=15) #nrows, ncols = len(rows)+1, len(columns)+1 #hcell, wcell = 1, 1 #hpad, wpad = .5, 0 #fig = figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad)) #fig = figure() #ax = fig.add_subplot(111) #ax.axis('off') #ax.table(cellText=table_data, # rowLabels=rows, # colLabels=columns, # loc='center') show() close()
def save_table(table_data, save_name, columns): if len(table_data) > 0: col_colours = ['red'] * len(columns) the_table1 = plt.table(cellText=table_data, colWidths=[0.15] * len(columns), colLabels=columns, colColours=col_colours, loc='center', cellLoc="left") the_table1.auto_set_font_size(False) the_table1.set_fontsize(FONTSIZE) the_table1.scale(1, 2) for cell in the_table1._cells: # print(cell) if cell[1] == -1: the_table1._cells[cell].set_edgecolor(None) plt.axis('off') # plt.show() plt.savefig(image_path + os.sep + save_name) plt.cla()
def StabilityTable(self, fig=1): """ Displays the table of stability derivatives and their appropriate stable ranges. """ pyl.figure(fig) AsUnit = '%1.2f' colLabels = ('Phugoid', 'Short Period', 'Pure Pitching', 'Spiral Mode', 'Dutch Roll') rowLabels = ('Required', r'$\omega$ (1/s)', r'$\zeta$') #cellText = [[r'0.04 < $\zeta$',r'0.35 < $\zeta$ < 1.3',r'1.0 < $\zeta$',r'$\zeta$ 12s or negative',r'0.08 < $\zeta$; 0.4 < $\omega$']] cellText = [[ r'0.04 < $\zeta$', r'0.35 < $\zeta$ < 1.3', r'1.0 < $\zeta$', r'"$\zeta$" >20s or <0', r'0.08 < $\zeta$; 0.4 < $\omega$' ]] Freq = [ self.LongPeriodFreq() / (1 / SEC), self.ShortPeriodFreq() / (1 / SEC), self.PitchFreq() / (1 / SEC), self.SpiralMode() / (1 / SEC), self.DutchRollFreq() / (1 / SEC) ] Damp = [ self.LongPeriodDamp(), self.ShortPeriodDamp(), self.PitchDamp(), self.SpiralDoubleTime() / (SEC), self.DutchRollDamp() ] cellText.append([AsUnit % Freq[i] for i in range(len(Freq))]) cellText.append([AsUnit % Damp[i] for i in range(len(Damp))]) colWidths = self._GetTableColWidths(rowLabels, cellText, colLabels) # # Mark any values outside of the appropriate range # cellColours = [] for r in cellText: cellColours.append(['w' for i in range(len(r))]) # # Frequencies # # cellColours[1][3] = 'w' if 0.0 < Freq[3] else 'r' cellColours[1][4] = 'w' if 0.4 < Freq[4] else 'r' # # Damping rates # cellColours[2][0] = 'w' if 0.04 < Damp[0] else 'r' cellColours[2][ 1] = 'w' if 0.35 < Damp[1] and Damp[1] < 1.3 else 'r' cellColours[2][ 2] = 'w' if 1.0 < Damp[2] else 'y' if 0.8 < Damp[2] else 'r' cellColours[2][3] = 'w' if 12.0 < Damp[3] or Damp[3] < 0.0 else 'r' cellColours[2][4] = 'w' if 0.08 < Damp[4] else 'r' pyl.axes([0.01, 0.01, 0.99, 0.95]) pyl.axis('off') table = pyl.table( cellText=cellText, cellColours=cellColours, rowLabels=rowLabels, #rowColours=colours, colWidths=colWidths, colLabels=colLabels, colLoc='center', loc='upper right') table.auto_set_font_size(False) table.set_fontsize(11) table.scale(1., 1.7) #------------------------------------------------------------------ # Second table #------------------------------------------------------------------ AsUnit = '%1.4f' colLabels = ['Roll Reversal', r'$C_{n\beta}$ Dynamic'] rowLabels = ['Required', r'Value'] cellText = [[r'0 < ', r'0 < ']] Values = [ self.RollReversal(), (self.CnbDynamic(-20 * ARCDEG), self.CnbDynamic(25 * ARCDEG)) ] cellText.append([AsUnit % v for v in Values[:-1]]) cellText[-1].append((AsUnit % Values[-1][0]) + ', ' + (AsUnit % Values[-1][1])) colWidths = self._GetTableColWidths(rowLabels, cellText, colLabels) # # Mark any values outside of the appropriate range # cellColours = [] for r in cellText: cellColours.append(['w' for i in range(len(r))]) # # Mark them as red # cellColours[1][0] = 'w' if 0.00 < Values[0] else 'r' cellColours[1][1] = 'w' if 0.00 < Values[-1][0] and 0.00 < Values[ -1][1] else 'r' table = pyl.table( cellText=cellText, cellColours=cellColours, rowLabels=rowLabels, #rowColours=colours, colWidths=colWidths, colLabels=colLabels, colLoc='center', loc='center right') table.auto_set_font_size(False) table.set_fontsize(11) table.scale(1., 1.7) #------------------------------------------------------------------ # Third table #------------------------------------------------------------------ AsUnit = '%1.3f' colLabels = [ r'$C_{m\alpha}$', r'$C_{mq}$', r'$C_{m \delta e}$', r'$C_{n\beta}$', r'$C_{n \delta r}$', r'$C_{l \beta}$', r'$C_{l \delta a}$' ] rowLabels = [' '] cellText = [] try: Aileron_Cl = self.Aileron.Cl except ParamKeyError: Aileron_Cl = 0 Values = [ self.Cma, self.Cmq, self.Elevator.Cm, self.Cnb, self.Rudder.Cn, self.Clb, Aileron_Cl ] cellText.append([AsUnit % v for v in Values]) colWidths = self._GetTableColWidths(rowLabels, cellText, colLabels) # # Just set all colors to white # cellColours = [] for r in cellText: cellColours.append(['w' for i in range(len(r))]) table = pyl.table( cellText=cellText, cellColours=cellColours, rowLabels=rowLabels, #rowColours=colours, colWidths=colWidths, colLabels=colLabels, colLoc='center', loc='lower right') table.auto_set_font_size(False) table.set_fontsize(11) table.scale(1., 1.7)
def ControlsTables(self, fig=1): """ Display the control derivatives for the control surfaces """ pyl.figure(fig) pyl.axes([0.01, 0.01, 0.99, 0.95]) pyl.axis('off') loc = ['upper right', 'center right', 'lower right'] n = 0 for ControlName in self.param.ControlSurfaces: Control = self.__dict__[ControlName] AsUnit = '%1.6f' colLabels = ACControls._ACControlSurfDeriv._Coefficients rowLabels = [ControlName] cellText = [] cellText.append([ AsUnit % (Control.__dict__[Deriv] / (1 / ARCDEG)) for Deriv in ACControls._ACControlSurfDeriv._Coefficients ]) colWidths = self._GetTableColWidths(rowLabels, cellText, colLabels) # # Mark any values outside of the appropriate range # cellColours = [] for r in cellText: cellColours.append(['w' for i in range(len(r))]) # # Frequencies # # cellColours[1][3] = 'w' if 0.0 < Freq[3] else 'r' #cellColours[1][4] = 'w' if 0.4 < Freq[4] else 'r' # # Damping rates # #cellColours[2][0] = 'w' if 0.04 < Damp[0] else 'r' #cellColours[2][1] = 'w' if 0.35 < Damp[1] and Damp[1] < 1.3 else 'r' #cellColours[2][2] = 'w' if 1.0 < Damp[2] else 'y' if 0.8 < Damp[2] else 'r' #cellColours[2][3] = 'w' if 12.0 < Damp[3] or Damp[3] < 0.0 else 'r' #cellColours[2][4] = 'w' if 0.08 < Damp[4] else 'r' table = pyl.table( cellText=cellText, cellColours=cellColours, rowLabels=rowLabels, #rowColours=colours, colWidths=colWidths, colLabels=colLabels, colLoc='center', loc=loc[n]) table.label = ControlName table.auto_set_font_size(False) table.set_fontsize(11) table.scale(1., 1.7) fig += 1 n += 1
codes.sort() # a 16,16 array of character strings chars = [['' for c in range(16)] for r in range(16)] colors = [[0.95 for c in range(16)] for r in range(16)] figure(figsize=(8, 4), dpi=120) for glyphind, ccode in codes: if ccode >= 256: continue r, c = divmod(ccode, 16) s = chr(ccode) chars[r][c] = s lightgrn = (0.5, 0.8, 0.5) title(fontname) tab = table(cellText=chars, rowLabels=labelr, colLabels=labelc, rowColours=[lightgrn] * 16, colColours=[lightgrn] * 16, cellColours=colors, cellLoc='center', loc='upper left') for key, cell in tab.get_celld().items(): row, col = key if row > 0 and col > 0: cell.set_text_props(fontproperties=FontProperties(fname=sys.argv[1])) axis('off') show()
pl.tight_layout() ''' ''' col_labels=['volume','length'] row_labels=['TF','LCFS','ratio'] table_vals=[[r'{:1.0f}m$^3$'.format(rb.TFvol),r'{:1.1f}m'.format(rb.TFlength)], [r'{:1.0f}m$^3$'.format(rb.Pvol),r'{:1.1f}m'.format(rb.Plength)], ['{:1.2f}'.format(rb.Rvol),r'{:1.2f}'.format(rb.Rlength)]] cell_colours = np.chararray(np.shape(table_vals)) for i in range(np.shape(table_vals)[0]): for j in range(np.shape(table_vals)[1]): cell_colours[i,j] = 'w' pl.table(cellText=table_vals,colWidths=[0.2]*3,rowLabels=row_labels, colLabels=col_labels,loc='bottom right', alpha=1,bbox=[0.6, 0.05, 0.4, 0.15],fontsize=24, cellColours=cell_colours.decode()) ''' ''' a = pl.axes([0.18, 0.1, .5, .14]) Color = cycle(sns.color_palette('Set2')) for leg,ha,va in zip(conf.targets.keys(),['right','left'],['bottom','bottom']): color = next(Color) target = rb.targets[leg] if 'L3D' in target.keys(): pl.plot(target['L2D'],target['L3D'],color=color) pl.text(target['L2D'][-1],target['L3D'][-1], ' '+leg+' {:1.1f}m'.format(target['L3D'][-1]), ha=ha,va=va,color=color)
def plot_single_maps(players, teamnum, teamname): c = get_colors() pylab.figure(1).clf() map_pool = ['Antiga', 'Testbug', 'Dual', 'Metalopolis', 'XelNaga',\ 'Shakuras', 'Daybreak', 'Shattered'] num_players = 0 for player in players: if player.maps: num_players += 1 data = [] for player in range(0, num_players): mappas = [] for i in range(0, len(map_pool)): mappas.append(0) data.append(mappas) i = 0 p = [] for player in players: if player.maps: p.append(player.character) maps = [] for key in sorted(player.maps.keys()): for m in map_pool: if m in key: map_index = map_pool.index(m) data[i][map_index] = int(player.maps[key]) i += 1 #ind = [0, 1, 2, 3, 4, 5, 6, 7] ind = numpy.arange(len(map_pool)) width = 1.0/num_players bars = [] cellText = [] for player in range(0, num_players): bars.append(pylab.bar(ind+(player*width), data[player], width, color=c[player])) cellText.append(['%d' % x for x in data[player]]) #for i in range(0, len(map_pool)): # pylab.xticks(i, map_pool[i]) rowLabels = ['Antiga', 'Testbug', 'Dual', 'Meta', 'XNC', 'Shakur', 'Dayb', 'Shattered'] pylab.xticks(range(8), rowLabels, size='small') pylab.yscale=('linear') pylab.legend(bars, p) pylab.grid(b=True, which='major', axis='both') pylab.title('Maps for 1v1 Games ' + teamname) pylab.xlabel('Maps') pylab.ylabel('Number of Times Played') pylab.savefig(os.path.join(SAVEDIR, str(teamnum) + '_1v1maps.png')) #pylab.figure(1).clf() cellText.reverse() c.reverse() table = pylab.table(cellText=cellText, rowLabels=p, colLabels=rowLabels) pylab.savefig(os.path.join(SAVEDIR, str(teamnum) + '_1v1maps_table.pdf'))
def report(self): """ Plot a visual report of the progress made so far in the experiment. """ # Sync with the REST server self._sync_with_server() # Report historical progress and results assumed pending import matplotlib.pyplot as plt # Get outcome values and put them in order of their IDs, # which should be equivalent to chronological order (of suggestion time) ids = np.array(self._ids_to_outcome_values.keys()) outcomes_values = np.array(self._ids_to_outcome_values.values()) # Clean up nans, infs and Nones outcomes_values = np.array( map(lambda x: float(x) if x is not None else -np.inf, outcomes_values)) outcomes_values[np.logical_not(np.isfinite(outcomes_values))] = -np.inf s = ids.argsort() ids = ids[s] outcome_values = outcomes_values[s] outcome_values = np.array([float(i) for i in outcome_values]) if outcome_values.size == 0 or np.all(np.isinf(outcome_values)): print('There are no completed results to report') return # Plot progression plt.figure(1) plt.clf() y = outcome_values best_so_far = [np.max(y[:(i + 1)]) for i in range(len(y))] plt.scatter(range(len(y)), y, marker='x', color='k', label='Outcomes') plt.plot(range(len(y)), best_so_far, color='k', label='Best so far') plt.xlabel('Result #') plt.ylabel(self.outcome_name) plt.title('Results progression') plt.legend(loc=3) plt.draw() plt.ion() plt.show() # Plot table of results plt.figure(2) param_names = list(np.sort(self.parameters.keys())) col_names = ['Result #'] + param_names + [self.outcome_name] cell_text = [] for nb, id in enumerate(ids): # Get paramater values, put in correct order and add to # table with corresponding outcome value params, values = zip(*self._ids_to_param_values[id].items()) s = np.argsort(params) values = np.array(values)[s] outcome = self._ids_to_outcome_values[id] cell_text.append([str(nb + 1)] + [str(v) for v in values] + [str(outcome)]) if len(cell_text) > 20: cell_text = cell_text[-20:] the_table = plt.table(cellText=cell_text, colLabels=col_names, loc='center') ## change cell properties table_props = the_table.properties() table_cells = table_props['child_artists'] for cell in table_cells: cell.set_fontsize(8) plt.axis('off') plt.title('Table of results') plt.draw() plt.ion() plt.show()
def report(self): """ Plot a visual report of the progress made so far in the experiment. """ # Sync with the REST server self._sync_with_server() # Report historical progress and results assumed pending import matplotlib.pyplot as plt # Get outcome values and put them in order of their IDs, # which should be equivalent to chronological order (of suggestion time) ids = np.array(self._ids_to_outcome_values.keys()) outcomes_values = np.array(self._ids_to_outcome_values.values()) # Clean up nans, infs and Nones outcomes_values = np.array(map(lambda x: float(x) if x is not None else -np.inf, outcomes_values)) outcomes_values[np.logical_not(np.isfinite(outcomes_values))] = -np.inf s = ids.argsort() ids = ids[s] outcome_values = outcomes_values[s] outcome_values = np.array([float(i) for i in outcome_values]) if outcome_values.size == 0 or np.all(np.isinf(outcome_values)): print('There are no completed results to report') return # Plot progression plt.figure(1) plt.clf() y = outcome_values best_so_far = [ np.max(y[:(i+1)]) for i in range(len(y)) ] plt.scatter(range(len(y)),y,marker='x',color='k',label='Outcomes') plt.plot(range(len(y)),best_so_far,color='k',label='Best so far') plt.xlabel('Result #') plt.ylabel(self.outcome_name) plt.title('Results progression') plt.legend(loc=3) plt.draw() plt.ion() plt.show() # Plot table of results plt.figure(2) param_names = list(np.sort(self.parameters.keys())) col_names = ['Result #'] + param_names + [self.outcome_name] cell_text = [] for nb,id in enumerate(ids): # Get paramater values, put in correct order and add to # table with corresponding outcome value params, values = zip(*self._ids_to_param_values[id].items()) s = np.argsort(params) values = np.array(values)[s] outcome = self._ids_to_outcome_values[id] cell_text.append([str(nb+1)] + [str(v) for v in values] + [str(outcome)]) if len(cell_text) > 20: cell_text = cell_text[-20:] the_table = plt.table(cellText = cell_text, colLabels=col_names, loc='center') ## change cell properties table_props=the_table.properties() table_cells=table_props['child_artists'] for cell in table_cells: cell.set_fontsize(8) plt.axis('off') plt.title('Table of results') plt.draw() plt.ion() plt.show()
fig = pylab.figure(figsize=(8, 6)) g_main = gridspec.GridSpec(rows, cols) # Slug Test Table Test columns = [ 'Date', 'Static Water\nLevel (ft bgs)', 'Slug Vol.\n(ft3)', 'Screen Interval', 'Representative\nHydraulic Conductivity (m/d)' ] row_label = ['Slug Test\nResults'] contents = [['Sep 16, 2017', 60, 0.1, '50 - 50.5', 1000]] table_test = fig.add_subplot(g_main[3:, 7:]) table_test.set_xticks([]) table_test.set_yticks([]) table_test.set_frame_on(False) pylab.table(cellText=contents, colLabels=columns, rowLabels=row_label, colWidths=[0.18] * 6, loc='center') location = pl.subplot(g_main[0:2, :4]) pl.xticks(()) pl.yticks(()) location_string = str( 'E 571,430.74 m E N 149,817.82 m NAD83(91)\n' + 'Ground Surface Elevation (brass cap): 140.528 m NAD83\n' + 'Total Depth = 108 ft Below Ground Surface (bgs)\n' + 'Type of Drilling Rig: Cable Tool w/Drive Barrel') pl.text(0.01, 0.95, location_string, ha='left', va='top', size=5.8) title = pl.subplot(g_main[0, 4:8]) pl.xticks(()) pl.yticks(())
py.annotate('Pin Distance: ' + dist2, xy=(0,.36),xycoords='data') py.annotate('Outer Diameter: ' + dia2, xy=(0,.3),xycoords='data') py.ylim(0,1) py.axis('off') #py.axis('scaled') py.subplot(122) img=mpimg.imread(SN + '.jpg') imgplot = py.imshow(img, origin='upper') py.axis('off') py.savefig(SN + 'data.png', dpi = 400) Image.open(SN + 'data.png').save(SN + 'data.jpg','JPEG',quality=95) os.system('rm ' + SN + '.png') os.system('rm ' + SN + '.jpg') py.figure(3,figsize=(5,6)) img=mpimg.imread(SN + 'data.jpg') imgplot = py.imshow(img, origin='upper') the_table = py.table(cellText=table_vals1) py.axis('off') py.savefig(SN + '.png', dpi = 400) Image.open(SN + '.png').save('JPEG/' + SN + '.jpg','JPEG',quality=95) os.system('rm ' + SN +'.png') os.system('rm ' + SN + 'data.png') os.system('rm ' + SN + 'data.jpg') #===========================================================================
chars = [["" for c in range(16)] for r in range(16)] colors = [[(0.95, 0.95, 0.95) for c in range(16)] for r in range(16)] figure(figsize=(8, 4), dpi=120) for ccode, glyphind in codes: if ccode >= 256: continue r, c = divmod(ccode, 16) s = unichr(ccode) chars[r][c] = s lightgrn = (0.5, 0.8, 0.5) title(fontname) tab = table( cellText=chars, rowLabels=labelr, colLabels=labelc, rowColours=[lightgrn] * 16, colColours=[lightgrn] * 16, cellColours=colors, cellLoc="center", loc="upper left", ) for key, cell in tab.get_celld().items(): row, col = key if row > 0 and col > 0: cell.set_text_props(fontproperties=FontProperties(fname=fontname)) axis("off") show()
def plot_single_maps(players, teamnum, teamname): c = get_colors() pylab.figure(1).clf() map_pool = ['Antiga', 'Testbug', 'Dual', 'Metalopolis', 'XelNaga',\ 'Shakuras', 'Daybreak', 'Shattered'] num_players = 0 for player in players: if player.maps: num_players += 1 data = [] for player in range(0, num_players): mappas = [] for i in range(0, len(map_pool)): mappas.append(0) data.append(mappas) i = 0 p = [] for player in players: if player.maps: p.append(player.character) maps = [] for key in sorted(player.maps.keys()): for m in map_pool: if m in key: map_index = map_pool.index(m) data[i][map_index] = int(player.maps[key]) i += 1 #ind = [0, 1, 2, 3, 4, 5, 6, 7] ind = numpy.arange(len(map_pool)) width = 1.0 / num_players bars = [] cellText = [] for player in range(0, num_players): bars.append( pylab.bar(ind + (player * width), data[player], width, color=c[player])) cellText.append(['%d' % x for x in data[player]]) #for i in range(0, len(map_pool)): # pylab.xticks(i, map_pool[i]) rowLabels = [ 'Antiga', 'Testbug', 'Dual', 'Meta', 'XNC', 'Shakur', 'Dayb', 'Shattered' ] pylab.xticks(range(8), rowLabels, size='small') pylab.yscale = ('linear') pylab.legend(bars, p) pylab.grid(b=True, which='major', axis='both') pylab.title('Maps for 1v1 Games ' + teamname) pylab.xlabel('Maps') pylab.ylabel('Number of Times Played') pylab.savefig(os.path.join(SAVEDIR, str(teamnum) + '_1v1maps.png')) #pylab.figure(1).clf() cellText.reverse() c.reverse() table = pylab.table(cellText=cellText, rowLabels=p, colLabels=rowLabels) pylab.savefig(os.path.join(SAVEDIR, str(teamnum) + '_1v1maps_table.pdf'))
def draw_shapefile(df, shapefile_path=r"C:\Users\KLYG\python\citymap\安阳市\Anyang", save_name="Anyang"): file = shapefile.Reader(shapefile_path) for city_rcd in file.shapeRecords(): # 遍历每一条shaperecord date1 = df["acq_date"] csv_name = city_rcd.record[12] + r"MODIS-24小时" + date1[0].replace( "/", "_") + "-" + date1[date1.size - 1].replace("/", "_") lon1 = file.bbox[0] lat1 = file.bbox[1] lon2 = file.bbox[2] lat2 = file.bbox[3] print(lon1, lat1, lon2, lat2) m = Basemap(llcrnrlon=lon1, llcrnrlat=lat1, urcrnrlon=lon2, urcrnrlat=lat2, projection='cyl') in_shape_points = [] not_in_shape_points = [] latitudes = [] longitudes = [] indexs = [] table_data = [] rds = file.shapeRecords() for index, row in df.iterrows(): lat = row['latitude'] lon = row['longitude'] if lon < lon1 or lon > lon2 or lat < lat1 or lat > lat2: pass else: print(lon, lat) latitudes.append(lat) longitudes.append(lon) indexs.append(index) table_data.append(row.values) pt = (lon, lat) if geometry.Point(pt).within(geometry.shape(rds[0].shape)): in_shape_points.append(pt) print(pt) else: # not_in_shape_points.append(pt) pass selected_lon = [elem[0] for elem in in_shape_points] selected_lat = [elem[1] for elem in in_shape_points] m.readshapefile(shapefile_path, 'whatevername', color='gray') m.scatter(selected_lon, selected_lat, latlon=True, s=30, marker="o", color='red') # m.scatter(114, 22.5, latlon=True, s=60, marker="o") # 这是一个测试点 # m.drawmeridians(np.arange(10, 125, 0.5), labels=[1, 0, 0, 1]) # m.drawparallels(np.arange(15, 30, 0.3),labels=[1,0,0,0]) #画纬度平行线 # plt.axis('off') # plt.show() plt.savefig(image_path + os.sep + save_name) if indexs.__len__() > 0: plt.clf() row_colors = ['red'] * df.shape[1] col_colours = ['red'] * df.shape[1] the_table1 = plt.table(cellText=table_data, colWidths=[0.15] * df.shape[1], colLabels=df.columns, colColours=col_colours, loc='center', cellLoc="left") the_table1.auto_set_font_size(False) the_table1.set_fontsize(10) the_table1.scale(1, 2) for cell in the_table1._cells: # print(cell) if cell[1] == -1: the_table1._cells[cell].set_edgecolor(None) plt.axis('off') plt.show() plt.savefig(image_path + os.sep + csv_name) plt.clf()
columns=['Fresh','Milk','Grocery','Frozen', 'Detergents_Paper','Delicatessen'] rows=['Customer 1','Customer 2','Customer 3'] colors = ['#3636ff','#36ff36','#ff3636'] data=[[26373,36423,22019,5154,4337,16523], [16165,4230,7595,201,4003,57], [14276,803,3045,485,100,518]] pylab.figure(figsize=(12,7)) pylab.ylabel('Value'); pylab.xticks([]); x=numpy.arange(len(columns))+0.2 y=numpy.array([0.0]*len(columns)) bar_width=0.5; cell_text=[] for i in range(len(rows)): pylab.bar(x,data[i],bar_width,bottom=y,color=colors[i]) y=y+data[i]; cell_text.append(['%1.0f'%(d)for d in data[i]]) pylab.table(cellText=cell_text,rowLabels=rows, rowColours=colors,colLabels=columns,loc='bottom') pylab.title('Samples of the Wholesale Customers Dataset') pylab.subplots_adjust(left=0.1,bottom=0.05); pylab.show() from sklearn.feature_extraction.text import CountVectorizer corpus=['Have you already set your goals for the New Year?', 'Do you want to lose ten kilos, run a marathon or speak fluent English?', 'Some experts believe that you need systems, not goals.', 'A system is something you do on a regular basis. ', 'This means focusing on what you can control (your actions) rather than what you can’t.', 'For example, do not focus on losing ten kilos.', 'Focus on shopping for healthy food and cooking something light every day.', 'Do not focus on the marathon.', 'Focus on the training schedule.', 'Invent a system to improve your English, one step at a time.', 'Good luck!']