def view_board(np_data, fmt='{:s}', bkg_colors=['pink', 'pink']): data = pd.DataFrame(np_data, columns=['0','1','2','3','4','5','6']) fig, ax = plt.subplots(figsize=[7,7]) ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = data.shape width, height = 1.0 / ncols, 1.0 / nrows for (i,j), val in np.ndenumerate(data): idx = [j % 2, (j + 1) % 2][i % 2] color = bkg_colors[idx] tb.add_cell(i, j, width, height, text=fmt.format(val), loc='center', facecolor=color) for i, label in enumerate(data.index): tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none') for j, label in enumerate(data.columns): tb.add_cell(-1, j, width, height/2, text=label, loc='center', edgecolor='none', facecolor='none') tb.set_fontsize(24) ax.add_table(tb) return fig
def __init__(self, xy, axes=None, bbox=None): Table.__init__(self, axes or plt.gca(), bbox=bbox) self.xy = xy self.set_transform(self._axes.transData) self._fixed_widhts = None import matplotlib.pyplot as plt self.max_fontsize = plt.rcParams.get("font.size", 12)
def __draw(self, state: dict): """ Draw 2-D sudoku board as image. Parameter ------------ state: dict A sudoku board in dictionary form. """ _, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) width = height = 1.0 / 9 for key in self.state.keys(): # Add cells i, j = self.__display_table_map[key] tb.add_cell(i, j, width, height, text='{}'.format(state[key]), loc='center', facecolor=self.__color_map[key]) ax.add_table(tb) plt.show()
def print_policy(policy, i): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.ylim(MAX_CAR_LOC_1, 0) plt.yticks(np.arange(MAX_CAR_LOC_1, -1, step=-5)) plt.xticks(np.arange(0, MAX_CAR_LOC_2 + 1, step=5)) tb = Table(ax) plt.title(r"$π_" + str(i) + "$") nrows, ncols = policy.shape width, height = 1.0 / ncols, 1.0 / nrows policy = np.flip(policy, axis=0) for (i, j), val in np.ndenumerate(policy): tb.add_cell(row=i, col=j, width=width, height=height, text=str(policy[i, j]), loc='center', facecolor=dict_action_color[abs(policy[i, j])]) ax.set_xlabel("Number car at second location", fontsize=12) ax.set_ylabel("Number car at first location", fontsize=12) ax.add_table(tb) plt.draw() while True: if plt.waitforbuttonpress(0): break plt.close(fig)
def plot_policy(ax: plt.Axes): ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) nrows, ncols = learner.value.shape width, height = 1.0 / ncols, 1.0 / nrows for (i, j) in np.ndindex(learner.value.shape): tb.add_cell(i, j, width, height) ax.add_table(tb) for idx in np.ndindex(learner.value.shape): if env.is_terminal(idx): continue actions = GridEnv.legal_actions(idx) returns = np.zeros_like(actions, dtype=np.float32) for i, action in np.ndenumerate(actions): new_state = env.step(idx, action) returns[i] = learner.value[new_state] for a in np.where(returns >= returns.max())[0]: add_arrow(ax, idx[0], idx[1], a, learner.value.shape) ax.set_xlim(0, 1) ax.set_ylim(0, 1)
def draw(self, renderer): Table.draw(self, renderer) # Add title if self.title != None: # Position using loc (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C, TR, TL, BL, BR, R, L, T, B) = range(len(self.codes)) # Get table bounds. bounds = self._get_grid_bbox(self._cachedRenderer).bounds y = bounds[1] + bounds[3] + self._approx_text_height() / 2 # Default for left x = bounds[0] ha = 'left' # Right if self._loc in (BEST, UR, LR, R, CR): x = bounds[0] + bounds[2] ha = 'right' # Center if self._loc in (LC, UC, C): x = bounds[0] + bounds[2] / 2.0 ha = 'center' # Create text object title = Text(x, y, text=self.title, ha=ha, va="bottom") title.set_figure(self.figure) title.set_transform(self.get_transform()) title.draw(self._cachedRenderer)
def _create_table(self): """Creates a table for displaying the entire field using matplotlib table.""" _, axis = plt.subplots() axis.set_axis_off() table = Table(axis, bbox=[0, 0, 1, 1]) try: width, height = 1.0 / self.rows, 1.0 / self.cols except ZeroDivisionError: # No table is going to be drawn, cols or rows is 0 return current_col = 0 while current_col < self.cols: for current_row in range(0, self.rows): value = self.data[current_row][current_col] cell = table.add_cell(current_col, current_row, width, height, text=value or "", loc='center') if value != MINE: text_color = self._get_color(value) cell.get_text().set_color(text_color) cell.get_text().set_fontsize(FONT_SIZE) current_col += 1 title = f"Game, W: {self.rows}, H: {self.cols}, Mines: {self.mines}" axis.set_title(title) axis.add_table(table)
def checkerboard_table(ax, region, fmt='{:.2f}'): loaded_region = region nrows = 18 ncolumns = 18 ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) colors = COLORS[:len(loaded_region)] width, height = 1.0 / ncolumns, 1.0 / nrows # Add cells row_index = 1 for unit_id in range(1, 18 * 18 + 1): column_index = unit_id % ncolumns column_index = column_index if column_index != 0 else ncolumns color_id = find_district_id_by_unit_id(loaded_region, unit_id) color = colors[color_id - 1] # facecolor - background color tb.add_cell(row_index, column_index, width, height, loc='center', facecolor=color) if column_index == ncolumns: row_index += 1 # Row Labels... for i in range(1, nrows + 1): tb.add_cell(i, -1, width, height, text=i, loc='right', edgecolor='none', facecolor='none') # Column Labels... for j in range(1, ncolumns + 1): tb.add_cell(-1, j, width, height / 2, text=j, loc='center', edgecolor='none', facecolor='none') tb.set_fontsize(16) ax.add_table(tb) color_patches = get_color_patches(colors) ax.legend(handles=color_patches, loc='upper center', bbox_to_anchor=(0.5, 0), shadow=True, ncol=4)
def __init__(self, ax, loc=None, bbox=None, title=None, offset=None): Table.__init__(self, ax, loc, bbox) self.title = title self.offset = offset if self.offset is None: self.offset = [0, 0] if self.title: self.offset[1] -= 0.075
def draw_q_value_image(dyna_maze, q_value, run, planning_steps, episode): # 축 표시 제거, 크기 조절 등 이미지 그리기 이전 설정 작업 fig, axis = plt.subplots() axis.set_axis_off() table = Table(axis, bbox=[0, 0, 1, 1]) num_rows, num_cols = dyna_maze.MAZE_HEIGHT, dyna_maze.MAZE_WIDTH width, height = 1.0 / num_cols, 1.0 / num_rows for i in range(dyna_maze.MAZE_HEIGHT): for j in range(dyna_maze.MAZE_WIDTH): if np.sum(q_value[i][j]) == 0.0: symbol = " " else: action_idx = np.argmax(q_value[i][j]) symbol = dyna_maze.ACTION_SYMBOLS[action_idx] table.add_cell(i, j, width, height, text=symbol, loc='center', facecolor='white') # 행, 열 라벨 추가 for i in range(dyna_maze.MAZE_HEIGHT): table.add_cell(i, -1, width, height, text=i, loc='right', edgecolor='none', facecolor='none') for j in range(dyna_maze.MAZE_WIDTH): table.add_cell(-1, j, width, height/2, text=j, loc='center', edgecolor='none', facecolor='none') for key, cell in table.get_celld().items(): cell.get_text().set_fontsize(20) axis.add_table(table) plt.savefig('images/maze_action_values_{0}_{1}_{2}.png'.format(run, planning_steps, episode)) plt.close()
def checkerboard_table(self, data, preyPosition): fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = data.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for i in range(self.boardSize[0]): for j in range(self.boardSize[1]): if(i == preyPosition[0] and j == preyPosition[1]): tb.add_cell(i, j, width, height, text=str(data[i][j]), loc='center', facecolor='yellow') else: tb.add_cell(i, j, width, height, text=str(data[i][j]), loc='center', facecolor='white') # Row Labels... for i in range(self.boardSize[0]): tb.add_cell(i, -1, width, height, text=str(i), loc='right', edgecolor='none', facecolor='none') # Column Labels... for j in range(self.boardSize[1]): tb.add_cell(-1, j, width, height/2, text=str(j), loc='center', edgecolor='none', facecolor='none') ax.add_table(tb)
def checkerboard_table(data, columns, rows, title, fmt='{:.2f}', logarea = 0.035): fig, ax = plt.subplots() plt.set_cmap('cool') ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) #plt.suptitle(title) nrows, ncols = data.shape width, height = 1.0 / ncols, 1.0 / nrows min_color = np.min(data)/logarea max_color = np.max(data)/logarea # Add cells for (i,j), val in np.ndenumerate(data): # Index either the first or second item of bkg_colors based on # a checker board pattern color = (val/logarea)/max_color print val if val > 0.0: tb.add_cell(i, j, width, height, text=fmt.format(val), loc='center', facecolor = str(1.0 - val/np.sum(data))) else: tb.add_cell(i, j, width, height) # Row Labels... for i in range(0,len(rows)): tb.add_cell(i, -1, width, height, text=rows[i], loc='top', edgecolor='none', facecolor='none') # Column Labels... for j in range(0,len(columns)): tb.add_cell(-1, j, width, height/2.0, text=columns[j], loc='left', edgecolor='none', facecolor='none') ax.add_table(tb) #.colorbar() return fig
def drawTable(data, rowLabels, columnLabels, max, isPositive, fmt='{:.2f}'): fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) nrows, ncols = data.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i, j), val in np.ndenumerate(data): # https://matplotlib.org/2.0.2/api/colors_api.html if isPositive: color = (1 - (data[i][j] / max), 1, 1 - (data[i][j] / max)) else: color = (1, 1 - (data[i][j] / max), 1 - (data[i][j] / max)) tb.add_cell(i, j, width, height, text=fmt.format(val), loc='center', facecolor=color) if j == 0: tb.add_cell(i, -1, width, height, text=rowLabels[i], loc='right', edgecolor='white', facecolor='white') if i == 0: tb.add_cell(-1, j, width, height / 2, text=columnLabels[j], loc='center', edgecolor='white', facecolor='white') tb.add_cell(-1, -1, width, height / 2, text="", loc='center', edgecolor='white', facecolor='white') ax.add_table(tb) return fig
def draw_grid_world_action_values_image(action_values, filename, GRID_HEIGHT, GRID_WIDTH, NUM_ACTIONS, ACTION_SYMBOLS): action_str_values = [] for i in range(GRID_HEIGHT): action_str_values.append([]) for j in range(GRID_WIDTH): str_values = [] for action in range(NUM_ACTIONS): str_values.append("{0} ({1}): {2:.2f}".format( ACTION_SYMBOLS[action], action, action_values[i, j, action])) action_str_values[i].append("\n".join(str_values)) # 축 표시 제거, 크기 조절 등 이미지 그리기 이전 설정 작업 fig, ax = plt.subplots() ax.set_axis_off() table = Table(ax, bbox=[0, 0, 1, 1]) nrows, ncols = GRID_HEIGHT, GRID_WIDTH width, height = 1.0 / ncols, 1.0 / nrows # 렌더링 할 이미지에 표 셀과 해당 값 추가 for i in range(GRID_HEIGHT): for j in range(GRID_WIDTH): table.add_cell(i, j, width, height, text=action_str_values[i][j], loc='center', facecolor='white') # 행, 열 라벨 추가 for i in range(len(action_str_values)): table.add_cell(i, -1, width, height, text=i + 1, loc='right', edgecolor='none', facecolor='none') table.add_cell(-1, i, width, height / 2, text=i + 1, loc='center', edgecolor='none', facecolor='none') for key, cell in table.get_celld().items(): cell.get_text().set_fontsize(10) ax.add_table(table) plt.savefig(filename) plt.close()
def test_table_cells(): fig, ax = plt.subplots() table = Table(ax) cell = table.add_cell(1, 2, 1, 1) assert isinstance(cell, CustomCell) assert cell is table[1, 2] cell2 = CustomCell((0, 0), 1, 2, visible_edges=None) table[2, 1] = cell2 assert table[2, 1] is cell2
def __init__(self, ax, df, colors): self._ax = ax self._df = df self._colors = colors # Create matplotlib's Table object self._tb = Table(self._ax, bbox=[0, 0, 1, 1]) self._tb.auto_set_font_size(False) self._ax.add_table(self._tb) self._calculate_cell_size() self._add_cells() self._remove_ticks()
def plotGrid(value, title): value = np.round(value, decimals=1) fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) nrows, ncols = value.shape width, height = 1.0 / ncols, 1.0 / nrows for (i, j), val in np.ndenumerate(value): tb.add_cell(i, j, width, height, text=val, loc='center') ax.add_table(tb) plt.title(title) plt.show()
def view_board(np_data, fmt='{:s}', bkg_colors=['pink', 'pink']): """ Remember to add a '-' sign to the cell that is the old move leading to the current state; :param np_data: numpy array of shape (9,9) :param fmt: format of the data :param bkg_colors: originally used for chess board with intermittent colors :return: """ data = pd.DataFrame(np_data, columns=['0', '1', '2', '3', '4', '5', '6', '7', '8']) fig, ax = plt.subplots(figsize=[9, 9]) ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) nrows, ncols = data.shape width, height = 1.0 / ncols, 1.0 / nrows for (i, j), val in np.ndenumerate(data): idx = [j % 2, (j + 1) % 2][i % 2] color = bkg_colors[idx] tb.add_cell(i, j, width, height, text=fmt.format(val), loc='center', facecolor=color) for i, label in enumerate(data.index): tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none') for j, label in enumerate(data.columns): tb.add_cell(-1, j, width, height / 2, text=label, loc='center', edgecolor='none', facecolor='none') tb.set_fontsize(24) ax.add_table(tb) return fig
def __make_table(self): ''' Transforms the filter model into a table. This code is based on the code in matplotlib.table :return: the table. ''' if len(self.__filter_model) > 0 and self.__magnitude_model is not None: fc = self.__magnitude_model.limits.axes_1.get_facecolor() cell_kwargs = {} if self.__filter_axes is not None: table_axes = self.__filter_axes table_loc = {'loc': 'center'} else: table_axes = self.__magnitude_model.limits.axes_1 table_loc = {'bbox': (self.x0.value(), self.y0.value(), self.x1.value() - self.x0.value(), self.y1.value() - self.y0.value())} # this is some hackery around the way the matplotlib table works # multiplier = 1.2 * 1.85 if not self.__first_create else 1.2 multiplier = self.filterRowHeightMultiplier.value() self.__first_create = False row_height = ( self.tableFontSize.value() / 72.0 * self.preview.canvas.figure.dpi / table_axes.bbox.height * multiplier) cell_kwargs['facecolor'] = fc table = Table(table_axes, **table_loc) table.set_zorder(1000) self.__add_filters_to_table(table, row_height, cell_kwargs) table.auto_set_font_size(False) table.set_fontsize(self.tableFontSize.value()) return table return None
def plot_show(sample_count): fig, ax = plt.subplots(figsize=(25,25)) ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) all_cards = get_all_cards() # nrows, ncols = len(label), len(label) nrows, ncols = len(all_cards), len(all_cards) width, height = 1.0 / ncols, 1.0 / nrows # Add cells for i in range(len(all_cards)): for j in range(len(all_cards)): if all_cards[i] == all_cards[j]: EHS_value = 0.0 else: EHS_value = computer_EHS([all_cards[i], all_cards[j]], sample_count) * 100 color = get_color(EHS_value) tb.add_cell(i+1, j, width, height, text=str(int(EHS_value)), loc='center', facecolor=color) # Row Labels... for i in range(len(all_cards)): tb.add_cell(i + 1, -1, width, height, text=all_cards[i], loc='right', edgecolor='none', facecolor='none') # Column Labels... for j in range(len(all_cards)): tb.add_cell(0, j, width, height / 2, text=all_cards[j], loc='center', edgecolor='none', facecolor='none') ax.add_table(tb) plt.title("EHS") plt.show()
def draw_image(image): fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) nrows, ncols = image.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i, j), val in np.ndenumerate(image): # add state labels if [i, j] == A_POS: val = str(val) + " (A)" if [i, j] == A_PRIME_POS: val = str(val) + " (A')" tb.add_cell(i, j, width, height, text=val, loc='center', facecolor='white') # Row and column labels... for i in range(len(image)): tb.add_cell(i, -1, width, height, text=i+1, loc='right', edgecolor='none', facecolor='none') for i in range(len(image[0])): tb.add_cell(-1, i, width, height/2, text=i+1, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb)
def plot_maze(ax): center = (60, 750) ax.arrow(*center, 0, 60, head_width=.5, head_length=10, length_includes_head=True, fc='k') ax.arrow(*center, 0, -60, head_width=.5, head_length=10, length_includes_head=True, fc='k') ax.arrow(*center, 3.5, 0, head_width=8, head_length=.6, length_includes_head=True, fc='k') ax.arrow(*center, -3.5, 0, head_width=8, head_length=.6, length_includes_head=True, fc='k') ax.text(center[0], center[1] - 100, 'actions', fontsize=10, horizontalalignment='center') H = 0.6 Δh, Δw = 1 / Maze.H, 1 / Maze.W tb = Table(ax, bbox=[20 / 65, H, 30 / 65, 1 - H]) for i in range(Maze.H): for j in range(Maze.W): t = '' if (i, j) == Maze.S: t = 'S' elif (i, j) == Maze.G: t = 'G' c = tb.add_cell(i, j, Δw, Δh, text=t, loc='center') c.set_lw(.5) c.set_fontsize(14) if (i, j) in Maze.OBSTACLE: c.set_fc('#aaaaaa') ax.add_table(tb)
def display(self, agent): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_axis_off() tb = Table(ax) nrows, ncols = self.world.shape width, height = 1.0 / ncols, 1.0 / nrows for (i, j), val in np.ndenumerate(self.world): if (i, j) == (agent.pos_y, agent.pos_x): tb.add_cell(row=i, col=j, width=width, height=height, facecolor=agent.color) elif (i, j) == self.ending_point: tb.add_cell(row=i, col=j, width=width, height=height, facecolor="red") else: tb.add_cell(row=i, col=j, width=width, height=height, text=self.dict_world_to_text[val], facecolor=self.dict_world_to_color[val], loc="center") ax.add_table(tb) plt.plot() plt.show()
def checkerboard_table(data, fmt='{:.2f}', bkg_colors=['yellow', 'white']): fig = plt.figure() ax = fig.add_subplot(111) ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = data.shape width, height = 1.0 / ncols, 1.0 / nrows # セル追加 for (i,j), val in np.ndenumerate(data): idx = [j % 2, (j + 1) % 2][i % 2] color = bkg_colors[idx] tb.add_cell(i, j, width, height, text=fmt.format(val), loc='center', facecolor=color) # 行ラベル for i, label in enumerate(data.index): tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none') # 列ラベル for j, label in enumerate(data.columns): tb.add_cell(-1, j, width, height/2, text=label, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb) return fig
def checkerboard_table(data, fmt='{:.2f}', bkg_colors=['yellow', 'white']): fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = data.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j), val in np.ndenumerate(data): # Index either the first or second item of bkg_colors based on # a checker board pattern idx = [j % 2, (j + 1) % 2][i % 2] color = bkg_colors[idx] tb.add_cell(i, j, width, height, text=val, loc='center', facecolor=color) # Row Labels... for i, label in enumerate(data.index): tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none') # Column Labels... for j, label in enumerate(data.columns): tb.add_cell(-1, j, width, height/2, text=label, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb) return fig
def draw_lat_matrix(fname, data, title="", lat_type=None, lat_types=None, columns=[], rows=[]): bkg_colors = ['#CCFFFF', 'white'] fmt = '{:.3f}' fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) nrows, ncols = data.shape assert nrows == len(rows) assert ncols == len(columns) width, height = 1.0 / ncols * 2, 1.0 / nrows * 2 for (i, j), val in np.ndenumerate(data): idx = [j % 2, (j + 1) % 2][i % 2] color = bkg_colors[idx] if val: if lat_type: txt = fmt.format(ls.exec_fn(val, lat_type)) else: assert lat_types txt = fmt.format(ls.exec_fn(val, lat_types[i])) else: txt = "-" tb.add_cell(i, j, width, height, text=txt, loc='center', facecolor=color) # Row Labels... for i, label in enumerate(rows): tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none') # Column Labels... for j, label in enumerate(columns): tb.add_cell(-1, j, width, height / 2, text=label, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb) if title: ax.set_title("\n".join(wrap(title)), y=1.08) savefig('../figs/' + fname + '.pdf', bbox_inches='tight') plt.close()
def draw_image(image): fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) nrows, ncols = image.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j), val in np.ndenumerate(image): # Index either the first or second item of bkg_colors based on # a checker board pattern idx = [j % 2, (j + 1) % 2][i % 2] color = 'white' tb.add_cell(i, j, width, height, text=val, loc='center', facecolor=color) # Row Labels... for i, label in enumerate(range(len(image))): tb.add_cell(i, -1, width, height, text=label+1, loc='right', edgecolor='none', facecolor='none') # Column Labels... for j, label in enumerate(range(len(image))): tb.add_cell(-1, j, width, height/2, text=label+1, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb)
def draw_image(image): plt.figure() ax = plt.gca() ax.set_axis_off() table = Table(ax, bbox=[0, 0, 1, 1]) width, height = 1.0 / world_size, 1.0 / world_size for i in range(world_size): for j in range(world_size): # image, i is x, j is y table.add_cell(j, i, width, height, text=image[i, j], loc='center') ax.add_table(table)
def show_grid(grid): fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) nrows, ncols = grid.shape width, height = 1.0/ncols, 1.0/nrows for (i, j), val in np.ndenumerate(grid): color = 'grey' if (i, j) == (0, 0) or (i, j) == (3, 3) else 'white' tb.add_cell(i, j, width, height, text="{0:.2f}".format(val), loc='center', facecolor=color) ax.add_table(tb) return ax
def draw_policy(optimal_values): fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) nrows, ncols = optimal_values.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i, j), val in np.ndenumerate(optimal_values): next_vals = [] for action in ACTIONS: next_state, _ = step([i, j], action) next_vals.append(optimal_values[next_state[0], next_state[1]]) best_actions = np.where(next_vals == np.max(next_vals))[0] val = '' for ba in best_actions: val += ACTIONS_FIGS[ba] # add state labels if [i, j] == A_POS: val = str(val) + " (A)" if [i, j] == A_PRIME_POS: val = str(val) + " (A')" if [i, j] == B_POS: val = str(val) + " (B)" if [i, j] == B_PRIME_POS: val = str(val) + " (B')" tb.add_cell(i, j, width, height, text=val, loc='center', facecolor='white') # Row and column labels... for i in range(len(optimal_values)): tb.add_cell(i, -1, width, height, text=i + 1, loc='right', edgecolor='none', facecolor='none') tb.add_cell(-1, i, width, height / 2, text=i + 1, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb)
def checkerboard_table(ax, data, fmt='{:.2f}'): BLUE = "#6475A6" RED = "#C02D16" nrows = data["rows"][0] ncolumns = data["columns"][0] ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) width, height = 1.0 / ncolumns, 1.0 / nrows # Add cells row_index = 1 for _, unit_data in enumerate(data["units"]): color = "lightgray" id_val = unit_data["id"] rep = unit_data["registration"]["rep"] column_index = id_val % ncolumns column_index = column_index if column_index != 0 else ncolumns if rep < 0.5: color = BLUE if rep > 0.5: color = RED # facecolor - background color tb.add_cell(row_index, column_index, width, height, text=fmt.format(rep), loc='center', facecolor=color) if column_index == ncolumns: row_index += 1 # Row Labels... for i in range(1, nrows + 1): tb.add_cell(i, -1, width, height, text=i, loc='right', edgecolor='none', facecolor='none') # Column Labels... for j in range(1, ncolumns + 1): tb.add_cell(-1, j, width, height / 2, text=j, loc='center', edgecolor='none', facecolor='none') tb.set_fontsize(16) ax.add_table(tb) blue_patch = mpatches.Patch(color=BLUE, label='Democratic units') red_patch = mpatches.Patch(color=RED, label='Republican units') white_patch = mpatches.Patch(color='lightgray', label='Even support') ax.legend(handles=[red_patch, blue_patch, white_patch], loc='upper center', bbox_to_anchor=(0.5, 0), shadow=True, ncol=2)
def test_table_cells(): fig, ax = plt.subplots() table = Table(ax) cell = table.add_cell(1, 2, 1, 1) assert isinstance(cell, CustomCell) assert cell is table[1, 2] cell2 = CustomCell((0, 0), 1, 2, visible_edges=None) table[2, 1] = cell2 assert table[2, 1] is cell2 # make sure gettitem support has not broken # properties and setp table.properties() plt.setp(table)
def test_table_cells(): fig, ax = plt.subplots() table = Table(ax) cell = table.add_cell(1, 2, 1, 1) assert isinstance(cell, CustomCell) assert cell is table[1, 2] cell2 = CustomCell((0, 0), 1, 2, visible_edges=None) table[2, 1] = cell2 assert table[2, 1] is cell2 # make sure getitem support has not broken # properties and setp table.properties() plt.setp(table)
def _build_states(self): self.t_ax = self.fig.add_axes([0.05, 0.05, .75, .9]) self.t_ax.set_axis_off() nrows = max(self.data['row']) ncols = max(self.data['column']) width = 1.0 / ncols height = 1.0 / nrows tb = Table(self.t_ax) for abb, row, col in zip(self.data['abbrev'], self.data['row'], self.data['column']): tb.add_cell(row-1, col-1, width, height, text=abb.upper(), edgecolor='b', loc='center') tb.set_fontsize(20) self.tb = self.t_ax.add_table(tb)
def square_table(data, fmt='{:.0f}'): fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = data.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j), val in np.ndenumerate(data): tb.add_cell(i, j, width, height, text=fmt.format(val), loc='center') """ # Row and Column Labels... for i, label in enumerate(data.columns): tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none') tb.add_cell(-1, i, width, height/2, text=label, loc='center', edgecolor='none', facecolor='none') """ ax.add_table(tb) return fig
def visualize_results_plate_class_membership(data, fmt='{:.2f}', bkg_colors=['cyan', 'white']): fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = data.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j), val in np.ndenumerate(data): # Index either the first or second item of bkg_colors based on a checker board pattern #idx = [j % 2, (j + 1) % 2][i % 2] #color = bkg_colors[idx] if (val > 0.5): color = bkg_colors[0] else: color = bkg_colors[1] tb.add_cell(i, j, width, height, text=fmt.format(val), loc='center', facecolor=color) # axis labels for rows ... for i, label in enumerate(string.ascii_uppercase[:nrows:]): tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none') # axis labels for cols ... for j, label in enumerate(data.columns): tb.add_cell(-1, j, width, height/2, text=label+1, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb) fig.suptitle("Visualize classification results - Plate with class memberships") return fig
def draw_image(image): fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = image.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j), val in np.ndenumerate(image): # Index either the first or second item of bkg_colors based on # a checker board pattern idx = [j % 2, (j + 1) % 2][i % 2] color = 'white' tb.add_cell(i, j, width, height, text=val, loc='center', facecolor=color) # Row Labels... for i, label in enumerate(range(len(image))): tb.add_cell(i, -1, width, height, text=label+1, loc='right', edgecolor='none', facecolor='none') # Column Labels... for j, label in enumerate(range(len(image))): tb.add_cell(-1, j, width, height/2, text=label+1, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb) plt.show()
def sort_fellows_table_pdf(names, jobs, companies, projects, subjects, unis, degs, name_plot): table = OrderedDict(( ('Name',names), ('Job',jobs), ('Company',companies), ('Project',projects), ('Subject',subjects), ('University', unis), ('Degree',degs))) Headn = ['Name','Job','Company','Project','Subject','University','Degree'] data = pandas.DataFrame(table) #print data fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = data.shape wcell = 1 hcell = 1 wpad = 0.5 hpad = 0.5 print "Making table" #fig = plt.figure(figsize=(5, 20)) width, height = 1.0 / (ncols*1.0), 1.0 / (nrows*2.0) matplotlib.rcParams.update({'font.size': 50}) print nrows, ncols # Add cells print data[Headn[1]].iloc[0] for i in range(0,ncols): for j in range(0,nrows-1): # Index either the first or second item of bkg_colors based on # a checker board pattern #idx = [j % 2, (j + 1) % 2][i % 2] txt = "\n".join(wrap(data[Headn[i]].iloc[j], 40)) nmrows = len(txt)/20.0 print len(txt), nmrows #raw_input('check') color = "white" tb.add_cell(j, i, width, height*2.0, text=txt, loc='center', facecolor="white") # Row Labels... for i in range(0,nrows-1): label = str(i) tb.add_cell(i, -1, width, height*2.0, text=label, loc='right', edgecolor='black', facecolor='lightblue') # Column Labels... for j, label in enumerate(data.columns): tb.add_cell(-1, j, width, height, text=label, loc='center', edgecolor='black', facecolor='lightcoral') ax.add_table(tb) plt.savefig(name_plot+'.pdf', bbox_inches = "tight") return ''
def probability_plot(probabilities, selected_sentence, dataset, ploting_path, top_n_probabilities=20, max_length=120): # Pyplot options fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) ncols = probabilities.shape[0] width, height = 1.0 / (ncols + 1), 1.0 / (top_n_probabilities + 1) # Truncate the time selected_sentence = selected_sentence[:max_length] probabilities = probabilities[:max_length] # Sort the frequencies sorted_indices = np.argsort(probabilities, axis=1) probabilities = probabilities[ np.repeat(np.arange(probabilities.shape[0])[ :, None], probabilities.shape[1], axis=1), sorted_indices][:, ::-1] # Truncate the probabilities probabilities = probabilities[:, :top_n_probabilities] for (i, j), _ in np.ndenumerate(probabilities): tb.add_cell(j + 1, i, height, width, text=unicode(str(conv_into_char(sorted_indices[i, j, 1], dataset)[0]), errors='ignore'), loc='center', facecolor=(1, 1 - probabilities[i, j, 0], 1 - probabilities[i, j, 0])) for i, char in enumerate(selected_sentence): tb.add_cell(0, i, height, width, text=unicode(char, errors='ignore'), loc='center', facecolor='green') ax.add_table(tb) plt.savefig(ploting_path)
def _on_gen_inst_button_click(self,b): self.gen_path_button.disabled=True self.gen_pos_button.disabled=False self.show_path_button.value='Path: Value: Actions:' for line in self.ax.lines: line.set_visible(False) del(line) #Instance Generation self.M=self.size_slider.value self.nb_ob=self.nb_ob_slider.value self.A=gen_rand_instance(self.M,self.M,self.nb_ob) self.G=gen_graph(self.A) if hasattr(self, 'ax'): # print self.ax self.ax.cla() if hasattr(self, 'start_circle'): del(self.start_circle) del(self.end_circle) del(self.arrow) colors=['white','grey'] self.ax.set_ylim([0,self.A.shape[0]]) self.ax.set_xlim([0,self.A.shape[1]]) self.ax.set_axis_off() self.tb = Table(self.ax, bbox=[0,0,1,1]) nrows, ncols = self.A.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j),val in np.ndenumerate(self.A): color=colors[val] self.tb.add_cell(i, j, width, height,loc='center', facecolor=color) # Row Labels... for i in range(self.A.shape[0]): self.tb.add_cell(i, -1, width, height, text=i, loc='right', edgecolor='none', facecolor='none') # Column Labels for j in range(self.A.shape[1]): self.tb.add_cell(-1, j, width, height/2, text=j, loc='center', edgecolor='none', facecolor='none') self.ax.add_table(self.tb) self.ax.invert_yaxis() #self.leg=self.ax.legend(bbox_to_anchor=(1.3, 1.05),fancybox=True) #self.leg.get_frame().set_alpha(0.5) #self.ax.legend() plt.show()
def show_interface(result,A,startPos,endPos): colors=['white','grey'] fig=plt.figure(figsize=(10,10)) ax=plt.subplot(111) ax.set_ylim([0,A.shape[0]]) ax.set_xlim([0,A.shape[1]]) ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = A.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j),val in np.ndenumerate(A): color=colors[val] tb.add_cell(i, j, width, height,loc='center', facecolor=color) # Row Labels... for i in range(A.shape[0]): tb.add_cell(i, -1, width, height, text=i, loc='right', edgecolor='none', facecolor='none') # Column Labels for j in range(A.shape[1]): tb.add_cell(-1, j, width, height/2, text=j, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb) #Ajout Chemin for i,j in result[2]: ax.add_line(lines.Line2D((i[1],j[1]),(i[0],j[0]),linewidth=3,zorder=1)) #Ajout Depart start=startPos[:2][::-1] start_circle=Circle(start,radius=0.2,alpha=0.8, color='g',zorder=2,label='Position de Depart') ax.add_patch(start_circle) #Ajout Direction de Depart start_dir=startPos[2] start_posA=start if(start_dir==1): start_posB=(start_posA[0],start_posA[1]-1) if(start_dir==2): start_posB=(start_posA[0]+1,start_posA[1]) if(start_dir==3): start_posB=(start_posA[0],start_posA[1]+1) if(start_dir==4): start_posB=(start_posA[0]-1,start_posA[1]) arrow=FancyArrowPatch(start_posA,start_posB,arrowstyle='->',color='m',mutation_scale=15.0,lw=2,zorder=3,label='Sens de Depart') ax.add_patch(arrow) #Ajout Arrivee end=endPos[:2][::-1] end_circle=Circle(end,radius=0.2,alpha=0.9, color='r',zorder=2,label='Position d\'arrivee') ax.add_patch(end_circle) ax.invert_yaxis() ax.legend(bbox_to_anchor=(1.1, 1.05)) plt.show()
def run(self): self.parent.clear_plots() if self.data is None: length, tMin, tMax, fMin, fMax, lMin, lMax, peakF, peakL, peakT = ("",) * 10 else: length = len(self.data) tMin = format_time(self.extent.tMin, True) tMax = format_time(self.extent.tMax, True) fMin = format_precision(self.settings, freq=self.extent.fMin, fancyUnits=True) fMax = format_precision(self.settings, freq=self.extent.fMax, fancyUnits=True) lMin = format_precision(self.settings, level=self.extent.lMin, fancyUnits=True) lMax = format_precision(self.settings, level=self.extent.lMax, fancyUnits=True) peak = self.extent.get_peak_flt() peakF = format_precision(self.settings, freq=peak[0], fancyUnits=True) peakL = format_precision(self.settings, level=peak[1], fancyUnits=True) peakT = format_time(peak[2], True) text = [ ["Sweeps", "", length], ["Extents", "", ""], ["", "Start", tMin], ["", "End", tMax], ["", "Min frequency", fMin], ["", "Max frequency", fMax], ["", "Min level", lMin], ["", "Max level", lMax], ["Peak", "", ""], ["", "Level", peakL], ["", "Frequency", peakF], ["", "Time", peakT], ] table = Table(self.axes, loc="center") table.set_gid("table") rows = len(text) cols = len(text[0]) for row in xrange(rows): for col in xrange(cols): table.add_cell(row, col, text=text[row][col], width=1.0 / cols, height=1.0 / rows) if self.settings.grid: colour = "LightGray" else: colour = "w" set_table_colour(table, colour) for i in range(3): table.auto_set_column_width(i) self.axes.add_table(table) self.parent.redraw_plot() self.parent.threadPlot = None
def probability_plot(probabilities, selected, vocab, ploting_path, top_n_probabilities=20, max_length=120): selected = selected[:max_length] probabilities = probabilities[:max_length] # target = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd'] # probabilities = np.random.uniform(low=0, high=1, size=(10, 6)) # T x C sorted_probabilities = np.zeros(probabilities.shape) sorted_indices = np.zeros(probabilities.shape) for i in range(probabilities.shape[0]): sorted_probabilities[i, :] = np.sort(probabilities[i, :]) sorted_indices[i, :] = np.argsort(probabilities[i, :]) concatenated = np.zeros(( probabilities.shape[0], probabilities.shape[1], 2)) concatenated[:, :, 0] = sorted_probabilities[:, ::-1] concatenated[:, :, 1] = sorted_indices[:, ::-1] fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) ncols = concatenated.shape[0] width, height = 1.0 / (ncols + 1), 1.0 / (top_n_probabilities + 1) for (i, j), v in np.ndenumerate(concatenated[:, :top_n_probabilities, 0]): tb.add_cell(j + 1, i, height, width, text=unicode(vocab[concatenated[i, j, 1].astype('int')], errors='ignore'), loc='center', facecolor=(1, 1 - concatenated[i, j, 0], 1 - concatenated[i, j, 0])) for i, char in enumerate(selected): tb.add_cell(0, i, height, width, text=unicode(char, errors='ignore'), loc='center', facecolor='green') ax.add_table(tb) plt.savefig(ploting_path)
def sort_fellows_table_nproj_pdf(names, jobs, companies, subjects, unis, degs, name_plot): table = OrderedDict(( ('Name',names), ('Job',jobs), ('Company',companies), ('Subject',subjects), ('University', unis), ('Degree',degs))) Headn = ['Name','Job','Company', 'Subject','University','Degree'] data = pandas.DataFrame(table) #print data fig, ax = plt.subplots() ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = data.shape #fig = plt.figure(figsize=(5, 20)) width, height = 1.0 / (ncols), 1.0 / (nrows) matplotlib.rcParams.update({'font.size': 20}) print nrows, ncols # Add cells print data[Headn[1]].iloc[0] for i in range(0,ncols): for j in range(0,nrows-1): txt = "\n".join(wrap(data[Headn[i]].iloc[j], 40)) color = "white" tb.add_cell(j, i, width, height, text=txt, loc='center', facecolor="white") # Row Labels... for i in range(0,nrows-1): label = str(i) tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='black', facecolor='lightblue') # Column Labels... for j, label in enumerate(data.columns): tb.add_cell(-1, j, width, height/2.0, text=label, loc='center', edgecolor='black', facecolor='lightcoral') ax.add_table(tb) plt.savefig(name_plot+'.pdf', bbox_inches = "tight") return ''
def replot_grid(self): self.colors=['white','grey'] self.ax.set_ylim([0,self.A.shape[0]]) self.ax.set_xlim([0,self.A.shape[1]]) self.ax.set_axis_off() self.tb = Table(self.ax, bbox=[0,0,1,1]) nrows, ncols = self.A.shape self.width, self.height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j),val in np.ndenumerate(self.A): color=self.colors[val] self.tb.add_cell(i, j, self.width, self.height,loc='center', facecolor=color) # Row Labels... for i in range(self.A.shape[0]): self.tb.add_cell(i, -1, self.width, self.height, text=i, loc='right', edgecolor='none', facecolor='none') # Column Labels for j in range(self.A.shape[1]): self.tb.add_cell(-1, j, self.width, self.height/2, text=j, loc='center', edgecolor='none', facecolor='none') self.ax.add_table(self.tb) self.ax.invert_yaxis() plt.draw()
def draw_lat_matrix(fname,data,title="",lat_type=None,lat_types=None,columns=[],rows=[]): bkg_colors=['#CCFFFF','white'] fmt='{:.3f}' fig,ax=plt.subplots() ax.set_axis_off() tb=Table(ax,bbox=[0,0,1,1]) nrows,ncols=data.shape assert nrows==len(rows) assert ncols==len(columns) width, height = 1.0 / ncols * 2, 1.0 / nrows * 2 for (i,j),val in np.ndenumerate(data): idx = [j % 2, (j + 1) % 2][i % 2] color = bkg_colors[idx] if val: if lat_type: txt=fmt.format(ls.exec_fn(val,lat_type)) else: assert lat_types txt=fmt.format(ls.exec_fn(val,lat_types[i])) else: txt="-" tb.add_cell(i, j, width, height, text=txt, loc='center', facecolor=color) # Row Labels... for i, label in enumerate(rows): tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none') # Column Labels... for j, label in enumerate(columns): tb.add_cell(-1, j, width, height/2, text=label, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb) if title: ax.set_title("\n".join(wrap(title)), y=1.08) savefig('../figs/' + fname +'.pdf', bbox_inches='tight') plt.close()
def drawtable(data, rows, columns, title, folder='Table', rowname='',fmt='{:.2f}'): nrows = len(rows) ncols = len(columns) fig, ax = plt.subplots(figsize=(ncols+2,nrows+2)) ax.set_axis_off() rowlc='#F0F0F0' collc='#F0F0F0' cellc='#FFFFFF' ecol='#0000FF' font1 = FontProperties() font1.set_size('9') fontl = font1.copy() fontl.set_weight('bold') tb = Table(ax)#, bbox=[0.10,0.10,0.90,0.90]) tb.auto_set_font_size(False) #tb.set_fontsize(100.0) width, height = 0.95/(ncols+1), 0.95/(nrows+1) for i in range(nrows): tb.add_cell(i,-1, width*2, height, text=rows[i][:20], loc='right',edgecolor=ecol, facecolor=rowlc,fontproperties=fontl) # Column Labels for j in range(ncols): tb.add_cell(-1, j, width, height/1.5, text=columns[j][:10], loc='center', edgecolor=ecol, facecolor=collc,fontproperties=fontl) tb.add_cell(-1,-1, width*2, height/1.5, text=rowname[:10], loc='right',edgecolor=ecol, facecolor=rowlc,fontproperties=fontl) # Add cells for i in range(len(data)): for j in range(len(data[i])): val = data[i][j] tb.add_cell(i,j,width, height, text=fmt.format(val), loc='center', edgecolor=ecol, facecolor=cellc, fontproperties=font1) # Row Labels ax.add_table(tb) plt.savefig(folder+'/'+title+'.pdf') #plt.show() #sys.exit(0) plt.close()
def run(self): self.parent.clear_plots() if self.data is None: length, tMin, tMax, fMin, fMax, lMin, lMax, peakF, peakL, peakT = ('-',) * 10 else: length = len(self.data) tMin = format_time(self.extent.tMin, True) tMax = format_time(self.extent.tMax, True) fMin = format_precision(self.settings, freq=self.extent.fMin, fancyUnits=True) fMax = format_precision(self.settings, freq=self.extent.fMax, fancyUnits=True) lMin = format_precision(self.settings, level=self.extent.lMin, fancyUnits=True) lMax = format_precision(self.settings, level=self.extent.lMax, fancyUnits=True) peak = self.extent.get_peak_flt() peakF = format_precision(self.settings, freq=peak[0], fancyUnits=True) peakL = format_precision(self.settings, level=peak[1], fancyUnits=True) peakT = format_time(peak[2], True) text = [['Sweeps', '', length], ['Extent', '', ''], ['', 'Start', tMin], ['', 'End', tMax], ['', 'Min frequency', fMin], ['', 'Max frequency', fMax], ['', 'Min level', lMin], ['', 'Max level', lMax], ['Peak', '', ''], ['', 'Level', peakL], ['', 'Frequency', peakF], ['', 'Time', peakT], ] table = Table(self.axes, loc='center') table.set_gid('table') rows = len(text) cols = len(text[0]) fontProperties = FontProperties() fontProperties.set_weight('semibold') for row in xrange(rows): for col in xrange(cols): fp = fontProperties if col == 0 else None table.add_cell(row, col, text=text[row][col], fontproperties=fp, width=1.0 / cols, height=1.0 / rows) if self.settings.grid: colour = 'LightGray' else: colour = 'w' set_table_colour(table, colour) for i in range(2): table.auto_set_column_width(i) self.axes.add_table(table) self.parent.redraw_plot() self.parent.threadPlot = None
def make_tab_big(value_tab, col_tab, format_type = "cost", \ cmap = ["#4575b4", "#ffffbf", "#d73027"], figsize = (10,10)): """ """ measures = list(value_tab.columns) # User-defined colormap from blue to red, going through a darker colour cm2 = mcol.LinearSegmentedColormap.from_list("new", \ cmap) cnorm = mcol.Normalize(vmin = 0, vmax = 1) cpick = cm.ScalarMappable(norm = cnorm, cmap = cm2) fig, ax = plt.subplots() ax.set_axis_off() # Create the table (so that you can avoid colouring the ranks manually) tb = Table(ax, bbox=[0,0,1,1]) nrows, ncols = value_tab.shape width, height = 1.0 / (ncols+1), 1.0 / (nrows+1) for (i, j), val in np.ndenumerate(value_tab): colour = cpick.to_rgba(col_tab.ix[i, j]) alpha = 0.7 colour = (colour[0], colour[1], colour[2], alpha) text_colour = "White" #cpick.to_rgba(1 - col_tab.ix[i, j]) # Find the best text colour. # If green is greater than 190/255 then use black. # unless blue is greater than 150/255. #[a < 0.9 for (r, g, b, a) in colour] if (colour[1] > 190./255) & (colour[2] > 150./255): text_colour = "Black" if np.isnan(val): colour = "White" text_colour = "Black" #if measures[j] == "Livestock culled": # format_type = "culled" #else: # format_type = "cost" # Format value string formatted_val = formatval(val, measures[j], format_type) # Add cell to the table tb.add_cell(i, j+1, width, height, text = formatted_val, loc = 'right', facecolor = colour, edgecolor = 'none') # Set the font colour tb._cells[(i, j+1)]._text.set_color(text_colour) # Columns for j, label in enumerate(measures): tb.add_cell(-1, j+1, width, height, text=label, loc='center', edgecolor='none', facecolor='none') tb._cells[(-1, j+1)]._text.set_weight('bold') # 'Control' and 'Model' labels tb.add_cell(-1, 0, width, height, text='Model', loc='center', edgecolor='none', facecolor='none') tb._cells[(-1, 0)]._text.set_weight('bold') tb.add_cell(-1, -1, width, height, text=' Control', loc='center', edgecolor='none', facecolor='none') tb._cells[(-1, -1)]._text.set_weight('bold') # Rows for i, label in enumerate(value_tab.index.labels[1]): tb.add_cell(i, 0, width, height, \ text = value_tab.index.levels[1][label], \ loc='center', edgecolor='none', facecolor='none') # Add table to the current axes ax.add_table(tb) # Bigger rows controls = [ "Infected\npremises\nculling\n(IP)", "Dangerous\ncontacts\nculling\n(DC)", "Ring culling\nat 3km\n(RC)", "", "", "", ""] incr = float(len(controls)) for k, label in enumerate(controls): ax.text(-0.05, 1 - (k+1)/incr + 1./15., label, fontsize = 10, \ horizontalalignment = 'center', verticalalignment = 'center') if k < 4: pass else: ax.axhline(k/incr, -0.15, 1,c = "Black", clip_on = False) ax.axhline(2./incr, -0.15, 1,c = "Black", clip_on = False) ax.axhline(0./incr, -0.15, 1,c = "Black", clip_on = False) ax.axhline(1, -0.15, 1, c = "Black", clip_on = False) ax.axhline(3./incr, -0.02, 1,c = "Black", clip_on = False) ax.axhline(1./incr, -0.02, 1,c = "Black", clip_on = False) ax.text(-0.1, 1 - 4./incr, "Vaccinate\n at 3km", \ fontsize = 10, horizontalalignment = 'center', \ verticalalignment = 'center') ax.text(0.01, 1 - 4./incr + 1./15., "to live\n(V3L)", \ fontsize = 10, horizontalalignment = 'center', \ verticalalignment = 'center') ax.text(0.01, 1 - 5./incr + 1./15., "to kill\n(V3K)", \ fontsize = 10, horizontalalignment = 'center', \ verticalalignment = 'center') ax.text(-0.1, 1 - 6./incr, "Vaccinate\n at 10km", \ fontsize = 10, horizontalalignment = 'center', \ verticalalignment = 'center') ax.text(0.01, 1 - 6./incr + 1./15., "to live\n(V10L)", \ fontsize = 10, horizontalalignment = 'center', \ verticalalignment = 'center') ax.text(0.01, 1 - 7./incr + 1./15., "to kill\n(V10K)", \ fontsize = 10, horizontalalignment = 'center', \ verticalalignment = 'center') # Add the extra lines #ax.axhline(k/incr, -0.15, 1,c = "Black", clip_on = False) #ax.text(-0.05, 1 + 1./70 , 'Control', fontsize = 12, fontweight = 'bold',\ # horizontalalignment = 'center', verticalalignment = 'center') fig.set_size_inches(figsize) return fig, ax
def run(self): self.parent.clear_plots() if self.data is None: self.parent.threadPlot = None return tMin = format_time(self.extent.tMin, True) tMax = format_time(self.extent.tMax, True) fMin = format_precision(self.settings, freq=self.extent.fMin, fancyUnits=True) fMax = format_precision(self.settings, freq=self.extent.fMax, fancyUnits=True) lMin = format_precision(self.settings, level=self.extent.lMin, fancyUnits=True) lMax = format_precision(self.settings, level=self.extent.lMax, fancyUnits=True) peak = self.extent.get_peak_flt() peakF = format_precision(self.settings, freq=peak[0], fancyUnits=True) peakL = format_precision(self.settings, level=peak[1], fancyUnits=True) peakT = format_time(peak[2], True) text = [['Sweeps', '', len(self.data)], ['Extents', '', ''], ['', 'Start', tMin], ['', 'End', tMax], ['', 'Min frequency', fMin], ['', 'Max frequency', fMax], ['', 'Min level', lMin], ['', 'Max level', lMax], ['Peak', '', ''], ['', 'Level', peakL], ['', 'Frequency', peakF], ['', 'Time', peakT], ] table = Table(self.axes, loc='center', gid='table') rows = len(text) cols = len(text[0]) for row in xrange(rows): for col in xrange(cols): table.add_cell(row, col, text=text[row][col], width=1.0 / cols, height=1.0 / rows) if self.settings.grid: colour = 'LightGray' else: colour = 'w' set_table_colour(table, colour) for i in range(3): table.auto_set_column_width(i) self.axes.add_table(table) noData = find_artists(self.axes, 'noData') noData[0].set_alpha(0) self.parent.redraw_plot() self.parent.threadPlot = None
def table_plot(df, figsize=(12, 9), value_format='text', fontsize=None, positive_color=None, negative_color=None, header_color=None, index_color=None, fill_color=None, positive_fill_color=None, negative_fill_color=None, header_fill_color=None, index_fill_color=None, title=None, decimals=2, **kwargs): """ Plot DataFrame as a table Parameters ---------- df : DataFrame Data to be plotted as a table figsize : tuple, optional 2-ple of (x, y) dimensions for figures in inches value_format : string, optional Format of the table values. Options supported are 'text' and 'numeric'. fontsize : int, optional Font size positive_color : string, optional Color to print positive values negative_color : string, optional Color to print negative cells header_color : string, optional Color to print header values index_color : string, optional Color to print index values fill_color : string, optional Color to fill table cells positive_fill_color : string, optional Color to fill cells with positive values negative_fill_color : string, optional Color to fill cells with negative values header_fill_color : string, optional Color to fill header cells index_fill_color : string, optional Color to fill index cells title : string, optional Table title decimals : int, optional If value_format is numeric, the number of decimal places used to round values Returns ------- fig : Figure Figure containing the table plot """ if not isinstance(df, pd.DataFrame): raise TypeError('df should be a DataFrame object') if value_format not in ['text', 'numeric']: raise ValueError('%s is not a valid format' % value_format) # draw table fig, ax = plt.subplots(figsize=figsize) ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) num_cols, num_rows = len(df.columns), len(df.index) width, height = 1.0 / num_cols, 1.0 / num_rows # add table cells loc='center' for (i, j), val in np.ndenumerate(df): value = df.iloc[i, j] text_color = 'black' cell_color = 'none' if fill_color is not None: cell_color = fill_color if isinstance(value, int) or isinstance(value, float): if np.isnan(value): continue if positive_color is not None and value >= 0: text_color = positive_color if positive_fill_color is not None and value >= 0: cell_color = positive_fill_color if negative_color is not None and value < 0: text_color = negative_color if negative_fill_color is not None and value < 0: cell_color = negative_fill_color if value_format == 'text': tb.add_cell(i + 1, j + 1, width, height, text=str(val), loc=loc, facecolor=cell_color) elif value_format == 'numeric': value_str = str(round(val, decimals)) tb.add_cell(i + 1, j + 1, width, height, text=value_str, loc=loc, facecolor=cell_color) tb._cells[(i+1, j+1)]._text.set_color(text_color) elif isinstance(value, pd.tslib.Timestamp): tb.add_cell(i + 1, j + 1, width, height, text=val.strftime('%d-%b-%Y'), loc=loc, facecolor=cell_color) tb._cells[(i+1, j+1)]._text.set_color(text_color) else: tb.add_cell(i + 1, j + 1, width, height, text=str(val), loc=loc, facecolor=cell_color) tb._cells[(i+1, j+1)]._text.set_color(text_color) if index_color is None: index_color='black' if index_fill_color is not None: cell_color = index_fill_color else: cell_color = 'none' # row labels for i, label in enumerate(df.index): tb.add_cell(i + 1, 0, width, height, text=label, loc=loc, edgecolor='none', facecolor=cell_color) tb._cells[(i+1, 0)]._text.set_color(index_color) if header_color is None: header_color='black' if header_fill_color is not None: cell_color = header_fill_color else: cell_color = 'none' # column labels for j, label in enumerate(df.columns): tb.add_cell(0, j + 1, width, height, text=label, loc=loc, edgecolor='none', facecolor=cell_color) tb._cells[(i+1, 0)]._text.set_color(header_color) # set font size if fontsize is not None: tb_cells = tb.properties()['child_artists'] for cell in tb_cells: cell.set_fontsize(fontsize) # add table to figure ax.add_table(tb) # set title if title is not None: if fontsize is not None: ax.set_title(title, fontsize=fontsize) else: ax.set_title(title) plt.tight_layout() return fig
def shmoo_plotting(self): ''' pixel register shmoo plot ''' shmoopdf = PdfPages('shmoo.pdf') shmoonp = np.array(self.shmoo_errors) data = shmoonp.reshape(len(self.voltages),-1,order='F') fig, ax = plt.subplots() plt.title('Pixel registers errors') ax.set_axis_off() tb = Table(ax, bbox=[0,0,1,1]) ncols = len(self.bitfiles) nrows = len(self.voltages) width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j), val in np.ndenumerate(data): color = '' if val == 0: color = 'green' if (val > 0 & val < 10): color = 'yellow' if val > 10: color = 'red' tb.add_cell(i, j, width, height, text=str(val), loc='center', facecolor=color) # Row Labels... for i in range(len(self.voltages)): tb.add_cell(i, -1, width, height, text=str(self.voltages[i])+'V', loc='right', edgecolor='none', facecolor='none') # Column Labels... for j in range(len(self.bitfiles)): freq_label = self.bitfiles[j][-9:-7].translate(None, '_') tb.add_cell(nrows+1, j, width, height/2, text=freq_label+' MHz', loc='center', edgecolor='none', facecolor='none') ax.add_table(tb) shmoopdf.savefig() ''' global register shmoo plot ''' shmoo_glob_np = np.array(self.shmoo_global_errors) data_g = shmoo_glob_np.reshape(len(self.voltages),-1,order='F') fig_g, ax_g = plt.subplots() ax_g.set_axis_off() tb_g = Table(ax_g, bbox=[0,0,1,1]) plt.title('Global registers errors') # Add cells for (i,j), val_g in np.ndenumerate(data_g): color = '' if val_g == 0: color = 'green' if val_g > 0: color = 'red' tb_g.add_cell(i, j, width, height, text=str(val_g), loc='center', facecolor=color) # Row Labels... for i in range(len(self.voltages)): tb_g.add_cell(i, -1, width, height, text=str(self.voltages[i])+'V', loc='right', edgecolor='none', facecolor='none') # Column Labels... for j in range(len(self.bitfiles)): freq_label = self.bitfiles[j][-9:-7].translate(None, '_') tb_g.add_cell(nrows+1, j, width, height/2, text=freq_label+' MHz', loc='center', edgecolor='none', facecolor='none') ax_g.add_table(tb_g) shmoopdf.savefig() shmoopdf.close()
def mytable(ax, csize=0.04, cellText=None, cellColours=None, cellLoc='right', colWidths=None, rowLabels=None, rowColours=None, rowLoc='left', colLabels=None, colColours=None, colLoc='center', loc='bottom', bbox=None): # Check we have some cellText if cellText is None: # assume just colours are needed rows = len(cellColours) cols = len(cellColours[0]) cellText = [[''] * rows] * cols rows = len(cellText) cols = len(cellText[0]) for row in cellText: assert len(row) == cols if cellColours is not None: assert len(cellColours) == rows for row in cellColours: assert len(row) == cols else: cellColours = ['w' * cols] * rows # Set colwidths if not given if colWidths is None: colWidths = [1.0/cols] * cols # Check row and column labels rowLabelWidth = 0 if rowLabels is None: if rowColours is not None: rowLabels = [''] * cols rowLabelWidth = colWidths[0] elif rowColours is None: rowColours = 'w' * rows if rowLabels is not None: assert len(rowLabels) == rows offset = 0 if colLabels is None: if colColours is not None: colLabels = [''] * rows offset = 1 elif colColours is None: colColours = 'w' * cols offset = 1 if rowLabels is not None: assert len(rowLabels) == rows # Set up cell colours if not given if cellColours is None: cellColours = ['w' * cols] * rows # Now create the table table = Table(ax, loc, bbox) height = csize # Add the cells for row in xrange(rows): for col in xrange(cols): table.add_cell(row+offset, col, width=height, height=height, text=cellText[row][col], facecolor=cellColours[row][col], loc=cellLoc) ax.add_table(table) return table
class Interface(): def __init__(self,figsize=(6,6)): self.figsize=figsize self.size_slider=IntSlider(description='Grid Size',min=4,max=50) display(self.size_slider) self.nb_ob_slider=IntSlider(description='Obstacles',min=0,max=7) display(self.nb_ob_slider) self.gen_inst_button=Button(description='Generate Instance',margin=10) self.gen_pos_button=Button(description='Generate Start/End Positions',margin=10) self.gen_path_button=Button(description='Generate Path',margin=10) self.inst_but_container=HBox(children=[self.gen_inst_button,self.gen_pos_button,self.gen_path_button]) self.inst_but_container.width = '100%' display(self.inst_but_container) self.show_path_button=Latex(value='Path: Value: Actions:',margin=10) display(self.show_path_button) self.size_slider.on_trait_change(self._on_size_slider_change,'value') self.gen_inst_button.on_click(self._on_gen_inst_button_click) self.gen_pos_button.on_click(self._on_pos_button_click) self.gen_path_button.on_click(self._on_gen_path_button_click) self.gen_path_button.disabled=True self.gen_pos_button.disabled=True plt.close() plt.axis('off') self.fig=plt.figure(figsize=self.figsize) self.ax=self.fig.add_subplot(111) def _on_size_slider_change(self,name,value): self.nb_ob_slider.max=int(value)**2/2-4 #Constrain on number of obstacles def _on_gen_inst_button_click(self,b): self.gen_path_button.disabled=True self.gen_pos_button.disabled=False self.show_path_button.value='Path: Value: Actions:' for line in self.ax.lines: line.set_visible(False) del(line) #Instance Generation self.M=self.size_slider.value self.nb_ob=self.nb_ob_slider.value self.A=gen_rand_instance(self.M,self.M,self.nb_ob) self.G=gen_graph(self.A) if hasattr(self, 'ax'): # print self.ax self.ax.cla() if hasattr(self, 'start_circle'): del(self.start_circle) del(self.end_circle) del(self.arrow) colors=['white','grey'] self.ax.set_ylim([0,self.A.shape[0]]) self.ax.set_xlim([0,self.A.shape[1]]) self.ax.set_axis_off() self.tb = Table(self.ax, bbox=[0,0,1,1]) nrows, ncols = self.A.shape width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j),val in np.ndenumerate(self.A): color=colors[val] self.tb.add_cell(i, j, width, height,loc='center', facecolor=color) # Row Labels... for i in range(self.A.shape[0]): self.tb.add_cell(i, -1, width, height, text=i, loc='right', edgecolor='none', facecolor='none') # Column Labels for j in range(self.A.shape[1]): self.tb.add_cell(-1, j, width, height/2, text=j, loc='center', edgecolor='none', facecolor='none') self.ax.add_table(self.tb) self.ax.invert_yaxis() #self.leg=self.ax.legend(bbox_to_anchor=(1.3, 1.05),fancybox=True) #self.leg.get_frame().set_alpha(0.5) #self.ax.legend() plt.show() def _on_pos_button_click(self,b): for line in self.ax.lines: line.set_visible(False) del(line) self.gen_path_button.disabled=False self.start,self.end=gen_rand_positions(self.G) #Ajout Depart start_inst=self.start[:2][::-1] #Ajout Direction de Depart start_dir=self.start[2] start_posA=start_inst end_inst=self.end[:2][::-1] if(start_dir==1): start_posB=(start_posA[0],start_posA[1]-1) if(start_dir==2): start_posB=(start_posA[0]+1,start_posA[1]) if(start_dir==3): start_posB=(start_posA[0],start_posA[1]+1) if(start_dir==4): start_posB=(start_posA[0]-1,start_posA[1]) if hasattr(self, 'start_circle'): #deja trace self.start_circle.set_visible(True) self.end_circle.set_visible(True) self.arrow.set_visible(True) self.start_circle.center=start_inst self.arrow.set_positions(start_posA,start_posB) self.end_circle.center=end_inst self.show_path_button.value='Path: Value: Actions:' else: #jamais trace encore #Position de Depart self.start_circle=Circle(start_inst,radius=0.5,alpha=0.8, color='g',zorder=2,label='Depart',clip_on=False) self.ax.add_patch(self.start_circle) #Direction de Depart self.arrow=FancyArrowPatch(start_posA,start_posB,arrowstyle='->',color='m',mutation_scale=15.0,lw=2,zorder=3,clip_on=False) self.ax.add_patch(self.arrow) #Ajout Arrivee self.end_circle=Circle(end_inst,radius=0.5,alpha=0.8, color='r',zorder=2,label='Arrivee',clip_on=False) self.ax.add_patch(self.end_circle) self.leg=self.ax.legend(bbox_to_anchor=(1.1, 1.05),fancybox=True) self.leg.get_frame().set_alpha(0.5) plt.show() def _on_gen_path_button_click(self,b): self.gen_path_button.disabled=True self.result=gen_shortest_path(self.start,self.end,self.G) self.show_path_button.value='Path: Value: '+str(self.result[0])+' Actions: '+' '.join(e for e in self.result[1]) #Ajout Chemin for i,j in self.result[2]: self.ax.add_line(lines.Line2D((i[1],j[1]),(i[0],j[0]),linewidth=3,zorder=1,clip_on=False)) plt.draw()
def shmoo_plotting(self): ''' pixel register shmoo plot ''' shmoopdf = PdfPages('shmoo.pdf') shmoonp = np.array(self.shmoo_errors) data = shmoonp.reshape(len(self.voltages),-1,order='F') fig, ax = plt.subplots() plt.title('Pixel registers errors') ax.set_axis_off() fig.text(0.70, 0.05, 'SPI clock (MHz)', fontsize=14) fig.text(0.02, 0.90, 'Supply voltage (V)', fontsize=14, rotation=90) tb = Table(ax, bbox=[0.01,0.01,0.99,0.99]) ncols = len(self.bitfiles) nrows = len(self.voltages) width, height = 1.0 / ncols, 1.0 / nrows # Add cells for (i,j), val in np.ndenumerate(data): color = '' if val == 0: color = 'green' if (val > 0 & val < 10): color = 'yellow' if val > 10: color = 'red' tb.add_cell(i, j, width, height, text=str(val), loc='center', facecolor=color) # Row Labels... for i in range(len(self.voltages)): tb.add_cell(i, -1, width, height, text=str(self.voltages[i]), loc='right', edgecolor='none', facecolor='none') # Column Labels... for j in range(len(self.bitfiles)): newlabel1 = str(self.bitfiles[j][-9:-7]).replace("_","") tb.add_cell(nrows+1, j, width, height/2, text=newlabel1, loc='center', edgecolor='none', facecolor='none') ax.add_table(tb) shmoopdf.savefig() ''' global register shmoo plot ''' shmoo_glob_np = np.array(self.shmoo_global_errors) data_g = shmoo_glob_np.reshape(len(self.voltages),-1,order='F') fig_g, ax_g = plt.subplots() ax_g.set_axis_off() fig_g.text(0.70, 0.05, 'SPI clock (MHz)', fontsize=14) fig_g.text(0.02, 0.90, 'Supply voltage (V)', fontsize=14, rotation=90) tb_g = Table(ax_g, bbox=[0.01,0.01,0.99,0.99]) plt.title('Global registers errors') # Add cells for (i,j), val_g in np.ndenumerate(data_g): color = '' if val_g == 0: color = 'green' if val_g > 0: color = 'red' tb_g.add_cell(i, j, width, height, text=str(val_g), loc='center', facecolor=color) # Row Labels... for i in range(len(self.voltages)): tb_g.add_cell(i, -1, width, height, text=str(self.voltages[i]), loc='right', edgecolor='none', facecolor='none') # Column Labels... for j in range(len(self.bitfiles)): newlabel = str(self.bitfiles[j][-9:-7]).replace("_","") tb_g.add_cell(nrows+1, j, width, height/2, text=newlabel, loc='center', edgecolor='none', facecolor='none') ax_g.add_table(tb_g) shmoopdf.savefig() shmoopdf.close()
def type_table_plot(type_data): """ Plot type detail statistics table, save in png file. :param type_data: dataframe from get_type_detail(). """ groups = type_data.Group.values type_no_group = type_data.drop('Group', axis=1) nrows, ncols = type_no_group.shape width, height = 1.0 / ncols, 1.0 / nrows fig, ax = plt.subplots(figsize=(1, nrows*0.25)) ax.set_axis_off() tbl = Table(ax) tbl.auto_set_font_size(False) # Columns width for non-auto-width columns # col_widths = [1, 1, 0.5, 1, 0.7, 0.7, 0.7, 0.7, 0.7] palette = get_palette() fontcolor = 'w' fontsize = 9 for (i, j), val in np.ndenumerate(type_no_group): fc = palette[groups[i]] if j < 1: loc = 'left' font_family = None else: loc = 'center' font_family = 'DINPro' tbl.add_cell(i, j, width, height*0.7, text=val, loc=loc, facecolor=fc, edgecolor=fontcolor) cell = tbl.get_celld()[(i, j)] cell.set_linewidth(0.5) cell.set_text_props(color=fontcolor, family=font_family, weight='bold', fontsize=fontsize) # Column Labels... for j, label in enumerate(type_no_group.columns): tbl.add_cell(-1, j, width, height*0.7, text=label, loc='center', facecolor='gray', edgecolor='w') cell = tbl.get_celld()[(-1, j)] cell.set_linewidth(0.5) cell.set_text_props(color=fontcolor, weight='bold', family='Verdana', fontsize=9) tbl._autoColumns = range(ncols) tbl.scale(1, 1.55) # scale y to cover blank in the bottom ax.add_table(tbl) ax.margins(0, 0) fig.savefig('img/type_table', bbox_inches='tight', pad_inches=0.1, dpi=200)
def checkerboard_plot(ary, cell_colors=('white', 'black'), font_colors=('black', 'white'), fmt='%.1f', figsize=None, row_labels=None, col_labels=None, fontsize=None): """ Plot a checkerboard table / heatmap via matplotlib. Parameters ----------- ary : array-like, shape = [n, m] A 2D Nnumpy array. cell_colors : tuple or list (default: ('white', 'black')) Tuple or list containing the two colors of the checkerboard pattern. font_colors : tuple or list (default: ('black', 'white')) Font colors corresponding to the cell colors. figsize : tuple (default: (2.5, 2.5)) Height and width of the figure fmt : str (default: '%.1f') Python string formatter for cell values. The default '%.1f' results in floats with 1 digit after the decimal point. Use '%d' to show numbers as integers. row_labels : list (default: None) List of the row labels. Uses the array row indices 0 to n by default. col_labels : list (default: None) List of the column labels. Uses the array column indices 0 to m by default. fontsize : int (default: None) Specifies the font size of the checkerboard table. Uses matplotlib's default if None. Returns ----------- fig : matplotlib Figure object. """ fig, ax = subplots(figsize=figsize) ax.set_axis_off() tb = Table(ax, bbox=[0, 0, 1, 1]) n_rows, n_cols = ary.shape if row_labels is None: row_labels = np.arange(n_rows) if col_labels is None: col_labels = np.arange(n_cols) width, height = 1.0 / n_cols, 1.0 / n_rows for (row_idx, col_idx), cell_val in np.ndenumerate(ary): idx = (col_idx + row_idx) % 2 tb.add_cell(row_idx, col_idx, width, height, text=fmt % cell_val, loc='center', facecolor=cell_colors[idx]) for row_idx, label in enumerate(row_labels): tb.add_cell(row_idx, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none') for col_idx, label in enumerate(col_labels): tb.add_cell(-1, col_idx, width, height / 2., text=label, loc='center', edgecolor='none', facecolor='none') for (row_idx, col_idx), cell_val in np.ndenumerate(ary): idx = (col_idx + row_idx) % 2 tb._cells[(row_idx, col_idx)]._text.set_color(font_colors[idx]) ax.add_table(tb) tb.set_fontsize(fontsize) return fig
def plot(self, experiment, **kwargs): """Plot a table""" if not experiment: raise util.CytoflowViewError("No experiment specified") if not self.channel or self.channel not in experiment.data: raise util.CytoflowViewError("Must set a channel") if not (self.row_facet or self.column_facet): raise util.CytoflowViewError("Must set at least one of row_facet " "or column_facet") if self.subrow_facet and not self.row_facet: raise util.CytoflowViewError("Must set row_facet before using " "subrow_facet") if self.subcolumn_facet and not self.column_facet: raise util.CytoflowViewError("Must set column_facet before using " "subcolumn_facet") if self.row_facet and self.row_facet not in experiment.conditions: raise util.CytoflowViewError("Row facet {0} not in the experiment" .format(self.row_facet)) if self.subrow_facet and self.subrow_facet not in experiment.conditions: raise util.CytoflowViewError("Subrow facet {0} not in the experiment" .format(self.subrow_facet)) if self.column_facet and self.column_facet not in experiment.conditions: raise util.CytoflowViewError("Column facet {0} not in the experiment" .format(self.column_facet)) if self.subcolumn_facet and self.subcolumn_facet not in experiment.conditions: raise util.CytoflowViewError("Subcolumn facet {0} not in the experiment" .format(self.subcolumn_facet)) if not self.function: raise util.CytoflowViewError("Summary function isn't set") row_groups = np.sort(pd.unique(experiment[self.row_facet])) \ if self.row_facet else [None] subrow_groups = np.sort(pd.unique(experiment[self.subrow_facet])) \ if self.subrow_facet else [None] col_groups = np.sort(pd.unique(experiment[self.column_facet])) \ if self.column_facet else [None] subcol_groups = np.sort(pd.unique(experiment[self.subcolumn_facet])) \ if self.subcolumn_facet else [None] if self.subset: try: data = experiment.query(self.subset).data.reset_index() except: raise util.CytoflowViewError("Subset string '{0}' isn't valid" .format(self.subset)) if len(data.index) == 0: raise util.CytoflowViewError("Subset string '{0}' returned no events" .format(self.subset)) else: data = experiment.data group_vars = [] if self.row_facet: group_vars.append(self.row_facet) if self.subrow_facet: group_vars.append(self.subrow_facet) if self.column_facet: group_vars.append(self.column_facet) if self.subcolumn_facet: group_vars.append(self.subcolumn_facet) agg = data.groupby(by = group_vars)[self.channel].aggregate(self.function) # agg is a multi-index series; we can get a particular value from it # with get(idx1, idx2...) row_offset = (self.column_facet != "") + (self.subcolumn_facet != "") col_offset = (self.row_facet != "") + (self.subrow_facet != "") num_cols = len(col_groups) * len(subcol_groups) + col_offset fig = plt.figure() ax = fig.add_subplot(111) # hide the plot axes that matplotlib tries to make ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) for sp in ax.spines.itervalues(): sp.set_color('w') sp.set_zorder(0) loc = 'best' bbox = None t = Table(ax, loc, bbox, **kwargs) width = [1.0 / num_cols] * num_cols height = t._approx_text_height() * 1.8 # make the main table for (ri, r) in enumerate(row_groups): for (rri, rr) in enumerate(subrow_groups): for (ci, c) in enumerate(col_groups): for (cci, cc) in enumerate(subcol_groups): row_idx = ri * len(subrow_groups) + rri + row_offset col_idx = ci * len(subcol_groups) + cci + col_offset agg_idx = [x for x in (r, rr, c, cc) if x is not None] agg_idx = tuple(agg_idx) if len(agg_idx) == 1: agg_idx = agg_idx[0] t.add_cell(row_idx, col_idx, width = width[col_idx], height = height, text = agg.get(agg_idx)) # row headers if self.row_facet: for (ri, r) in enumerate(row_groups): row_idx = ri * len(subrow_groups) + row_offset text = "{0} = {1}".format(self.row_facet, r) t.add_cell(row_idx, 0, width = width[0], height = height, text = text) # subrow headers if self.subrow_facet: for (ri, r) in enumerate(row_groups): for (rri, rr) in enumerate(subrow_groups): row_idx = ri * len(subrow_groups) + rri + row_offset text = "{0} = {1}".format(self.subrow_facet, rr) t.add_cell(row_idx, 1, width = width[1], height = height, text = text) # column headers if self.column_facet: for (ci, c) in enumerate(col_groups): col_idx = ci * len(subcol_groups) + col_offset text = "{0} = {1}".format(self.column_facet, c) t.add_cell(0, col_idx, width = width[col_idx], height = height, text = text) # column headers if self.subcolumn_facet: for (ci, c) in enumerate(col_groups): for (cci, cc) in enumerate(subcol_groups): col_idx = ci * len(subcol_groups) + cci + col_offset text = "{0} = {1}".format(self.subcolumn_facet, c) t.add_cell(1, col_idx, width = width[col_idx], height = height, text = text) ax.add_table(t)