def get_gate_patch(self): '''Returns a matplotlib patch to be drawn on the canvas whose dimensions have been computed from the current gate. ''' x_min, x_max = self.subplot.get_xlim() x_range = x_max - x_min y_min, y_max = self.subplot.get_ylim() y_range = y_max - y_min for subgate in self.gate.get_subgates(): col = subgate.get_column() if col == self.x_column: x_min = subgate.get_min() x_range = subgate.get_max() - subgate.get_min() if col == self.y_column: y_min = subgate.get_min() y_range = subgate.get_max() - subgate.get_min() if self.patch not in self.subplot.patches: rect = Rectangle((x_min, y_min), x_range, y_range, animated=True) rect.set_fill(False) rect.set_linestyle('dashed') rect.set_edgecolor('dimgrey') self.patch = self.subplot.add_patch(rect) else: self.patch.set_bounds(x_min, y_min, x_range, y_range) return self.patch
def render(self,bgColor='w',obstacleColor='gray'): if not self.shown: plt.show() fig = plt.figure() ax = fig.add_subplot(111) rects = np.zeros((self.length,self.width), dtype = np.object) for i in np.arange(self.length): for j in np.arange(self.width): rect = Rectangle((i,j),1,1) ax.add_artist(rect) if self.obs[i,j]: rect.set_facecolor(obstacleColor) else: rect.set_facecolor(bgColor) rect.set_edgecolor('k') rects[i,j] = rect ax.set_xlim(0,self.length) ax.set_ylim(0,self.width) ax.set_aspect('equal','box') self.rects = rects self.fig = fig self.shown = True if self.lastvisited != None: self.rects[self.lastvisited[0],self.lastvisited[1]]. \ set_facecolor('b' if self.obs[self.lastvisited[0],self.lastvisited[1]] else 'g') self.rects[self.x,self.y].set_facecolor('r') self.lastvisited = (self.x,self.y) plt.pause(0.1) self.fig.canvas.draw() self.fig.canvas.flush_events()
def plot_extractions(data_sub, df_objects): """Plot the detected traces with rectangles on the input image """ # plot background-subtracted image fig, ax = plt.subplots() m, s = np.mean(data_sub), np.std(data_sub) im = ax.imshow(data_sub, interpolation='nearest', cmap='gray', vmin=m - s, vmax=m + s, origin='lower') # plot an ellipse for each object for i in range(len(df_objects)): if df_objects.poor_fit[i]: color = 'red' elif df_objects.saturated[i]: color = 'yellow' else: color = 'blue' e = Rectangle(xy=(df_objects.x[i] - 80, df_objects.y[i] - 18), width=160, height=10, angle=df_objects.theta[i] * 180. / np.pi) e.set_facecolor('none') e.set_edgecolor(color) ax.add_artist(e) plt.axis('off') plt.show()
def __fill_fibonacci_retracement_rectangle_dic__(self): index_left = self.xy[0, 0] index_right = self.xy[self.xy.shape[0] - 1, 0] value_left = self.xy[0, 1] value_right = self.xy[self.xy.shape[0] - 1, 1] value_range = value_right - value_left width = index_right - index_left for k in range( 0, len(fibonacci_helper.retracement_array_for_plotting) - 1): ret_01 = fibonacci_helper.retracement_array_for_plotting[k] ret_02 = fibonacci_helper.retracement_array_for_plotting[k + 1] value_01 = round(value_left + ret_01 * value_range, 2) value_02 = round(value_left + ret_02 * value_range, 2) height = value_02 - value_01 rectangle = Rectangle(np.array([index_left, value_01]), width=width, height=height) rectangle.set_linewidth(1) rectangle.set_linestyle('dashed') rectangle.set_color(self.color_list[k]) rectangle.set_edgecolor('k') rectangle.set_alpha(0.1) rectangle.set_visible(False) self.__fib_retracement_rectangle_dic[ret_02] = rectangle self.__fill_retracement_text_annotations__(index_left, ret_02, value_02) self.__fill_retracement_spikes_text_annotations__(ret_02, k + 1)
def draw(self): dpi = self.prefs['dpi'] ax_xsize = self.ax.get_window_extent().width ax_ysize = self.ax.get_window_extent().height nLabels = len(self.labels) nColumns = min(self.prefs['legend_max_columns'], int(ax_xsize / self.column_width)) maxRows = self.prefs['legend_max_rows'] nRows_ax = int(ax_ysize / 1.6 / self.prefs['text_size']) nRows_label = nLabels / nColumns + (nLabels % nColumns != 0) nRows = max(1, min(min(nRows_label, maxRows), nRows_ax)) self.ax.set_xlim(0., float(ax_xsize)) self.ax.set_ylim(-float(ax_ysize), 0.) legend_text_size, legend_text_padding = self.__get_legend_text_size() legend_text_size_point = pixelToPoint(legend_text_size, dpi) box_width = legend_text_size legend_offset = (ax_xsize - nColumns * self.column_width) / 2 nc = 0 # self.labels.reverse() for label, num in self.labels: num_flag = self.prefs.get('legend_numbers', True) percent_flag = self.prefs.get('legend_unit', '') if num_flag: if percent_flag == "%": num = "%.1f" % num + '%' else: num = "%.1f" % num else: num = None color = self.palette.getColor(label) row = nc % nRows column = int(nc / nRows) if row == nRows - 1 and column == nColumns - 1 and nc != nLabels - 1: last_text = '... plus %d more' % (nLabels - nc) self.ax.text(float(column * self.column_width) + legend_offset, -float(row * 1.6 * box_width), last_text, horizontalalignment='left', verticalalignment='top', size=legend_text_size_point) break else: self.ax.text(float(column * self.column_width) + 2. * box_width + legend_offset, -row * 1.6 * box_width, str(label), horizontalalignment='left', verticalalignment='top', size=legend_text_size_point) if num is not None: self.ax.text(float((column + 1) * self.column_width) - 2 * box_width + legend_offset, -float(row * 1.6 * box_width), str(num), horizontalalignment='right', verticalalignment='top', size=legend_text_size_point) box = Rectangle((float(column * self.column_width) + legend_offset, -float(row * 1.6 * box_width) - box_width), box_width, box_width) box.set_edgecolor('black') box.set_linewidth(pixelToPoint(0.5, dpi)) box.set_facecolor(color) self.ax.add_patch(box) nc += 1
def get_2d_box(mesh): x, width, y, height = get_2d_bounding_box(mesh) rect = Rectangle((x, y), width, height) rect.set_edgecolor('red') rect.set_facecolor('none') return rect
def __init__(self): self.state = 'Off' self.fig = plt.figure(figsize=(6, 6)) self.gamePlot = self.fig.add_subplot(111) self.gamePlot.axis('OFF') # declare canvas size self.margin = 10 self.width = 1000 self.height = 1000 ''' Exercise 4 Update the title of the game and make it yours! ''' ggt_title = 'Girls Go Tech 2020' # put text in the middle of the canvas self.gamePlot.text(0.5 * self.width, self.height + 20, ggt_title, horizontalalignment='center', verticalalignment='center', fontsize=10, color='black') # create white background with black edge background_rect = Rectangle((0, 0), self.width, self.height, color='white') background_rect.set_edgecolor('black') self.gamePlot.add_patch(background_rect) # create bricks self.brick_width = 80 self.brick_height = 40 self.bricks = [] self.create_bricks() ''' Exercise 5 The racket is moving a bit too slow right now. Adjust the speed of the racket to make the game more user-friendly. ''' # create racket self.racket_width = self.brick_width + 10 self.racket_height = self.brick_height / 2 self.move_unit = 5 self.racket_pos_y = 20 self.racket = Racket( (self.width / 2 - self.racket_width / 2, self.racket_pos_y), self.racket_width, self.racket_height, color='blue') self.gamePlot.add_patch(self.racket) self.gamePlot.set_xlim(0, self.width + self.margin) self.gamePlot.set_ylim(-self.margin, self.height) self.fig.canvas.mpl_connect('key_press_event', self.press)
def draw_rectangles(img, catalog, colnames=['x', 'y'], header=None, ax=None, rectangle_size=[30, 30], pixel_scale=0.168, color='r', **kwargs): if ax is None: fig = plt.figure(figsize=(12, 12)) fig.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0, wspace=0.00, hspace=0.00) gs = gridspec.GridSpec(2, 2) gs.update(wspace=0.0, hspace=0.00) ax1 = fig.add_subplot(gs[0]) else: ax1 = ax #ax1.yaxis.set_major_formatter(NullFormatter()) #ax1.xaxis.set_major_formatter(NullFormatter()) #ax1.axis('off') from matplotlib.patches import Rectangle if np.any([item.lower() == 'ra' for item in colnames]): if header is None: raise ValueError( '# Header containing WCS must be provided to convert sky coordinates into image coordinates.' ) return else: w = wcs.WCS(header) x, y = w.wcs_world2pix( Table(catalog)[colnames[0]].data.data, Table(catalog)[colnames[1]].data.data, 0) else: x, y = catalog[colnames[0]], catalog[colnames[1]] display_single(img, ax=ax1, pixel_scale=pixel_scale, **kwargs) for i in range(len(catalog)): e = Rectangle(xy=(x[i] - rectangle_size[0] // 2, y[i] - rectangle_size[1] // 2), height=rectangle_size[0], width=rectangle_size[1], angle=0) e.set_facecolor('none') e.set_edgecolor(color) e.set_alpha(0.7) e.set_linewidth(1.3) ax1.add_artist(e) if ax is not None: return ax
def add_conv_patch(self, conv1, conv2, patch_size=5, stride=1, size=3, ratio=None, direction=1): if ratio is None: ratio = [0.7, 0.5] start_loc = self.layers[conv1].get_xy() + np.array( (self.layers[conv1].get_width() * ratio[0], self.layers[conv1].get_height() * ratio[1])) end_loc = self.layers[conv2].get_xy() + np.array( (self.layers[conv2].get_width() * ratio[0], self.layers[conv2].get_height() * ratio[1])) # start_loc = top_left_list[ind_bgn] \ # + (num_show_list[ind_bgn] - 1) * np.array(loc_diff_list[ind_bgn]) \ # + np.array([start_ratio[0] * (size_list[ind_bgn][1] - patch_size[1]), # - start_ratio[1] * (size_list[ind_bgn][0] - patch_size[0])] # ) # end_loc = top_left_list[ind_bgn + 1] \ # + (num_show_list[ind_bgn + 1] - 1) * np.array( # loc_diff_list[ind_bgn + 1]) \ # + np.array([end_ratio[0] * size_list[ind_bgn + 1][1], # - end_ratio[1] * size_list[ind_bgn + 1][0]]) patch = Rectangle(start_loc, patch_size, -patch_size) patch.set_color(Dark * np.ones(3)) patch.set_edgecolor(Black * np.ones(3)) self.ax.add_patch(patch) line1 = Line2D([start_loc[0], end_loc[0]], [start_loc[1], end_loc[1]]) line1.set_color(Darker * np.ones(3)) self.ax.add_line(line1) line2 = Line2D([start_loc[0] + patch_size, end_loc[0]], [start_loc[1], end_loc[1]]) line2.set_color(Darker * np.ones(3)) self.ax.add_line(line2) line3 = Line2D([start_loc[0], end_loc[0]], [start_loc[1] - patch_size, end_loc[1]]) line3.set_color(Darker * np.ones(3)) self.ax.add_line(line3) line4 = Line2D([start_loc[0] + patch_size, end_loc[0]], [start_loc[1] - patch_size, end_loc[1]]) line4.set_color(Darker * np.ones(3)) self.ax.add_line(line4)
def plot_car(self, ax, car, marker_size=6): """Отрисовывает положение автомобиля и покзания GPS и одометрии. :param marker_size: Линейный размер точки положения и GPS-показания :param color: Цвет """ assert isinstance(car, Car) real_position_x = car._position_x real_position_y = car._position_y real_velocity_x = car._velocity_x real_velocity_y = car._velocity_y # Отрисовка реального положения центра автомобиля real_position = np.array([real_position_x, real_position_y]) self._plot_point(ax, real_position, marker='o', marker_color=self.real_color, marker_size=marker_size) # Отрисовка реального направления движения self.real_vel_ = ax.arrow(real_position_x, real_position_y, real_velocity_x, real_velocity_y, color=self.real_color, head_width=self.head_width) # Отрисовка "прямоугольника" автомобиля angle = np.arctan2(real_velocity_y, real_velocity_x) y_rec = real_position_y - 0.5 * (self.car_height * np.cos(angle) + self.car_width * np.sin(angle)) x_rec = real_position_x - 0.5 * (self.car_width * np.cos(angle) - self.car_height * np.sin(angle)) rec = Rectangle(xy=(x_rec, y_rec), width=self.car_width, height=self.car_height, angle=np.rad2deg(angle)) rec.set_facecolor('none') rec.set_edgecolor('k') ax.add_artist(rec) # Если установлен GPS-датчик, то отрисовать показания GPS if car.gps_sensor is not None: gps_noise_covariance = car.gps_sensor.get_noise_covariance() self._plot_ellipse(ax, car.gps_sensor.observe(), gps_noise_covariance, color=self.obs_color) self._plot_point(ax, car.gps_sensor.observe(), marker='*', marker_color=self.obs_color, marker_size=marker_size)
def plot_object(model, currentAxis=None, plot_point=None): plot_point_i = np.matmul(model.kinematics_equilibrium_dict['Cbi'].transpose(), plot_point) from matplotlib.patches import Rectangle import matplotlib.animation as animation rectangle = Rectangle((plot_point_i[0], plot_point_i[1]), model.object.a, model.object.b, angle=model.state_equilibrium_dict['theta']*180/np.pi, alpha=.35) rectangle.set_facecolor([0,0,1]) rectangle.set_edgecolor([0,0,0]) currentAxis.add_patch(rectangle) return currentAxis
def plot_rectangle(bboxes, ax, step, c='#ff7f0e'): for bbox in bboxes[bboxes['ts'] % step == 0]: s_phi_offset, c_phi_offset = np.sin(bbox['orientation']), np.cos(bbox['orientation']) rot = np.array([[c_phi_offset, - s_phi_offset], [s_phi_offset, c_phi_offset]]) offset_xy = np.dot(rot, 0.5 * bbox['dimension']) r = Rectangle(xy=bbox['center_xy'] - offset_xy, width=bbox['dimension'][0], height=bbox['dimension'][1], angle=np.rad2deg(bbox['orientation'])) ax.add_artist(r) r.set_clip_box(ax.bbox) r.set_alpha(0.8) r.set_facecolor('none') r.set_edgecolor(c)
def getField(ha, dec, height, width): """ Obtain rectangular patch corresponding to field of view """ x = ha - width / 2 y = dec - height / 2 r = Rectangle(xy=(x.hourangle, y.deg), width=width.hourangle, height=height.deg) r.set_facecolor('none') r.set_edgecolor('red') return r
def add_conv(self, dim, draw_size, depth=1, size=64, in_channels=1, out_channels=32, num=3): if self.previous_depth == depth: self.xy += np.array( (self.layers[-1].get_width() + self.layer_width, 0), dtype=float) elif self.previous_depth is not None and self.previous_depth < depth: self.xy += np.array( (self.layers[-1].get_width() - draw_size, -(self.layers[-1].get_height() + self.layer_width)), dtype=float) elif self.previous_depth is not None and self.previous_depth > depth: self.xy = np.array( (self.layers[-1].get_x() + 6, self.depth_xy[depth][1]), dtype=float) elif self.previous_depth is None: #Start self.xy -= np.array((self.layer_width, 0), dtype=float) self.depth_xy[depth] = self.xy.copy() self.depths[len(self.layers)] = depth conv_type = "Inputs" if len(self.layers) == 0 else "Channels" name = "{}\n{}@{}".format(conv_type, in_channels, "x".join(map(str, [size] * dim))) self._label(self.xy + np.array([0, draw_size]), name) for ind in xrange(num): #print ind * self.loc_diff patch = Rectangle(self.xy + ind * self.loc_diff, draw_size, draw_size) color = Medium if ind % 2 else Light patch.set_color(color * np.ones(3)) patch.set_edgecolor(Black * np.ones(3)) self.ax.add_patch(patch) if ind == num - 1: self.layers.append(patch) self.previous_depth = depth return len(self.layers) - 1
def drawSidewalk(obstacles, bgColor='w', obstacleColor='gray'): m = obstacles.shape[0] n = obstacles.shape[1] plt.show() fig = plt.figure() ax = fig.add_subplot(111) rects = np.zeros((m, n), dtype=np.object) for i in np.arange(m): for j in np.arange(n): rect = Rectangle((i, j), 1, 1) ax.add_artist(rect) if obstacles[i, j]: rect.set_facecolor(obstacleColor) else: rect.set_facecolor(bgColor) rect.set_edgecolor('k') rects[i, j] = rect ax.set_xlim(0, m) ax.set_ylim(0, n) ax.set_aspect('equal', 'box') return fig, ax, rects
class MainApp(App): def build(self): """ some initialization Args: rect: a dummy rectangle, whose width and height will be reset trigger by user event x0, y0: mouse click location x1, y1: mouse release location canvas: FigureCanvasKivyAgg object. Note that I'm using this back end right now as the FigureCanvas backend has bug with plt.show() selectors: store user-drawn rectangle data offsetx: translation of origin on x direction offsety: translation of origin on y direction """ self.selectors = [] img = mpimg.imread(sys.argv[1]) self.fig, self.ax = plt.subplots(1) plt.imshow(img) width, height = self.fig.canvas.get_width_height() pxorigin = self.ax.transData.transform([(0, 0)]) self.offsetx = pxorigin[0][0] self.offsety = height - pxorigin[0][1] print('offsetx, offsety', self.offsetx, self.offsety) self.rect = Rectangle((0, 0), 1, 1) self.rect.set_fill(False) self.rect.set_edgecolor('b') self.x0 = None self.y0 = None self.x1 = None self.y1 = None self.canvas = FigureCanvasKivyAgg( plt.gcf()) # get the current reference of plt box = BoxLayout() self.ax.add_patch(self.rect) # attach our rectangle to axis self.canvas.mpl_connect("button_press_event", self.on_press) self.canvas.mpl_connect("button_release_event", self.on_release) box.add_widget(self.canvas) return box def on_press(self, event): """ record user click location """ self.x0 = event.xdata self.y0 = event.ydata print('x0, y0', self.x0, self.y0) def on_release(self, event): """ record user mouse release location """ self.x1 = event.xdata self.y1 = event.ydata self.rect.set_width(self.x1 - self.x0) self.rect.set_height(self.y1 - self.y0) self.rect.set_xy((self.x0, self.y0)) xy_pixels = self.ax.transData.transform( np.vstack([self.x0, self.y0]).T) px, py = xy_pixels.T width, height = self.fig.canvas.get_width_height() # transform from origin on lower left to orgin on upper right py = height - py # account for translation factor px -= self.offsetx py -= self.offsety self.selectors.append( [px, py, abs(self.x1 - self.x0), abs(self.y1 - self.y0)]) print('your rectangle', px, py, abs(self.x1 - self.x0), abs(self.y1 - self.y0)) self.canvas.draw()
import matplotlib.pyplot as plt import numpy as np import numpy.random as npr import utilities_nopd as utils from matplotlib.font_manager import FontProperties from matplotlib.patches import Rectangle import colorbrewer as cb from mpltools import color legend_font = FontProperties() legend_font.set_size('small') ticks_font = FontProperties(family='Helvetica', style='normal', \ size=8, weight='normal', stretch='normal') empty_rect = Rectangle((0,0),1,1) empty_rect.set_alpha(0) empty_rect.set_edgecolor('white') color_scheme_names = ['BrBG', 'PiYG', 'PRGn', 'RdBu', 'RdGy', 'PuOr', \ 'RdYlBu', 'RdYlGn', 'Spectral'] color_schemes = {} for name in color_scheme_names: color_schemes[name] = eval('cb.{0}'.format(name)) def to_rgb(t): """ Args: t: 3-tuple of int's in range [0,255] Returns: out: 3-tuple of float's in range [0,1] """ r,g,b = np.array(t)/255.
plt.plot(ha_list, dec_list, 'c.', ms=3) # Add FOV if requested if args.fov: ha_fov = Longitude((lst - ra).wrap_at(12 * u.hourangle), u.hourangle) x = ha_fov - instrument.fov_ra / 2 y = dec_fov - instrument.fov_dec / 2 fov = Rectangle(xy=(x.hourangle, y.deg), width=instrument.fov_ra.hourangle, height=instrument.fov_dec.deg) fov.set_facecolor('red') fov.set_edgecolor('red') print('got here') ax.add_artist(fov) plt.title(str(time)) plt.xlabel('Hour angle / hr') plt.ylabel('Declination / $^\circ$') plt.xlim(-12, 12) plt.ylim(-33, 33) plt.show() input('enter')
def create_board_figure(pcb, bom_row, layer=pcbnew.F_Cu): qty, value, footpr, highlight_refs = bom_row plt.figure(figsize=(5.8, 8.2)) ax = plt.subplot("111", aspect="equal") color_pad1 = "lightgray" color_pad2 = "#AA0000" color_bbox1 = "None" color_bbox2 = "#E9AFAF" # get board edges (assuming rectangular, axis aligned pcb) edge_coords = [] for d in pcb.GetDrawings(): if (d.GetLayer() == pcbnew.Edge_Cuts): edge_coords.append(d.GetStart()) edge_coords.append(d.GetEnd()) edge_coords = np.asarray(edge_coords) * 1e-6 board_xmin, board_ymin = edge_coords.min(axis=0) board_xmax, board_ymax = edge_coords.max(axis=0) # draw board edges rct = Rectangle((board_xmin, board_ymin), board_xmax - board_xmin, board_ymax - board_ymin, angle=0) rct.set_color("None") rct.set_edgecolor("black") rct.set_linewidth(3) ax.add_patch(rct) # add title ax.text(board_xmin + .5 * (board_xmax - board_xmin), board_ymin - 0.5, "%dx %s, %s" % (qty, value, footpr), wrap=True, horizontalalignment='center', verticalalignment='bottom')\ # add ref list ax.text(board_xmin + .5 * (board_xmax - board_xmin), board_ymax + 0.5, ", ".join(highlight_refs), wrap=True, horizontalalignment='center', verticalalignment='top') # draw parts for m in pcb.GetModules(): if m.GetLayer() != layer: continue ref, center = m.GetReference(), np.asarray(m.GetCenter()) * 1e-6 highlight = ref in highlight_refs # bounding box mrect = m.GetFootprintRect() mrect_pos = np.asarray(mrect.GetPosition()) * 1e-6 mrect_size = np.asarray(mrect.GetSize()) * 1e-6 rct = Rectangle(mrect_pos, mrect_size[0], mrect_size[1]) rct.set_color(color_bbox2 if highlight else color_bbox1) rct.set_zorder(-1) if highlight: rct.set_linewidth(.1) rct.set_edgecolor(color_pad2) ax.add_patch(rct) # center marker if highlight: plt.plot(center[0], center[1], ".", markersize=mrect_size.min(), color=color_pad2) # plot pads for p in m.Pads(): pos = np.asarray(p.GetPosition()) * 1e-6 size = np.asarray(p.GetSize()) * 1e-6 * .9 shape = p.GetShape() offset = p.GetOffset() # TODO: check offset # pad rect angle = p.GetOrientation() * 0.1 cos, sin = np.cos(np.pi / 180. * angle), np.sin(np.pi / 180. * angle) dpos = np.dot([[cos, -sin], [sin, cos]], -.5 * size) if shape == 1: rct = Rectangle(pos + dpos, size[0], size[1], angle=angle) elif shape == 2: rct = Rectangle(pos + dpos, size[0], size[1], angle=angle) elif shape == 0: rct = Ellipse(pos, size[0], size[1], angle=angle) else: print("Unsupported pad shape") continue rct.set_color(color_pad2 if highlight else color_pad1) rct.set_zorder(1) ax.add_patch(rct) plt.xlim(board_xmin, board_xmax) plt.ylim(board_ymax, board_ymin) plt.axis('off')
def draw_rectangles(img, catalog, colnames=['x', 'y'], header=None, ax=None, rectangle_size=[30, 30], pixel_scale=0.168, color='r', **kwargs): """ Draw rectangles on an image according to a catalogue. Parameters: img (numpy 2-D array): Image itself. catalog (``astropy.table.Table`` object): A catalog which contains positions. colnames (list): List of string, indicating which columns correspond to positions. It can also be "ra" and "dec", but then "header" is needed. header: Header file of a FITS image containing WCS information, typically ``astropy.io.fits.header`` object. ax (``matplotlib.pyplot.axes`` object): The user could provide axes on which the figure will be drawn. rectangle_size (list of floats): Size of rectangles, in pixel. pixel_scale (float): Pixel size, in arcsec/pixel. Needed for correct scale bar. color (str): Color of rectangles. **kwargs: other arguments of ``display_single``. Returns: ax: If the input ``ax`` is not ``None``. """ if ax is None: fig = plt.figure(figsize=(12, 12)) fig.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0, wspace=0.00, hspace=0.00) gs = gridspec.GridSpec(2, 2) gs.update(wspace=0.0, hspace=0.00) ax1 = fig.add_subplot(gs[0]) else: ax1 = ax #ax1.yaxis.set_major_formatter(NullFormatter()) #ax1.xaxis.set_major_formatter(NullFormatter()) #ax1.axis('off') from matplotlib.patches import Rectangle if np.any([item.lower() == 'ra' for item in colnames]): if header is None: raise ValueError( '# Header containing WCS must be provided to convert sky coordinates into image coordinates.' ) return else: w = wcs.WCS(header) x, y = w.wcs_world2pix( Table(catalog)[colnames[0]].data.data, Table(catalog)[colnames[1]].data.data, 0) else: x, y = catalog[colnames[0]], catalog[colnames[1]] display_single(img, ax=ax1, pixel_scale=pixel_scale, **kwargs) for i in range(len(catalog)): e = Rectangle(xy=(x[i] - rectangle_size[0] // 2, y[i] - rectangle_size[1] // 2), height=rectangle_size[0], width=rectangle_size[1], angle=0) e.set_facecolor('none') e.set_edgecolor(color) e.set_alpha(0.7) e.set_linewidth(1.3) ax1.add_artist(e) if ax is not None: return ax
def _make_plot(self): """ """ self.axis.clear() scaler = self._make_scaler() logger.debug("{} fields on this coverage plot".format(len(self.fields))) sorted_field_indices = np.argsort([f.number_of_exposures for f in self.fields]) for idx in sorted_field_indices: # Sort the fields by number of observations, so the fields with more observations appear on top field = self.fields[idx] kwargs = self._field_kwargs[idx] # Compute the size of the field in the horizontal and vertical directions try: xsize = camera_size_degrees[0] / np.cos(field.dec.radians) ysize = camera_size_degrees[1] except AttributeError: # The field has no 'dec' continue # Compute the coordinates of the top left corner of the rectangle rec_x1 = ((field.ra.degrees + (camera_size_degrees[0] / np.cos(field.dec.radians)) / 2.) % 360.) * -1 + 180 # degrees rec_y1 = field.dec.degrees - camera_size_degrees[1] / 2. # degrees if kwargs.has_key("alpha"): alpha = kwargs["alpha"] del kwargs["alpha"] else: alpha = None if kwargs.has_key("color"): color = kwargs["color"] del kwargs["color"] else: # TODO: use scaler to get the color of this field if self.color_map == None: color = (0.,0.,0.,) if alpha == None: alpha = scaler(field.number_of_exposures)*0.5 + 0.1 else: self.color_map(scaler(field.number_of_exposures)) if alpha == None: alpha = 0.2 rec = Rectangle((np.radians(rec_x1), np.radians(rec_y1)), \ -np.radians(xsize), np.radians(ysize), \ color=color, alpha=alpha, **kwargs) rec.set_edgecolor("none") self.axis.add_patch(rec) if self.projection in ["aitoff", "hammer", "mollweide"]: self.axis.set_xticklabels([330, 300, 270, 240, 210, 180, 150, 120, 90, 60, 30]) if self.projection == "rectilinear": self.axis.set_xlim(-3.14159, 3.14159) self.axis.set_ylim(-3.14159/2., 3.14159/2) self.axis.legend(bbox_to_anchor=(0.8, 0.17), ncol=3, fancybox=True, shadow=True)
icol = (Omega+1)/2 icol=1-icol dicol = icol[1]-icol[0] AR_cb = 0.1 ialpha=np.abs(Omega)*5 ialpha[np.where(ialpha>1)]=1 w_cb = AR_cb*deltaOmega fig1=plt.figure(1,figsize=(3.4*0.25,3.4)) ax1=fig1.add_axes([0.3,0.1,0.8,0.8]) Rect_back = Rectangle((0,Omlims[0]),w_cb,deltaOmega) Rect_back.set_facecolor('k')#plt.cm.PuOr(icol)) Rect_back.set_edgecolor(None) ax1.add_artist(Rect_back) for ind in range(N-1): Rect = Rectangle((0,Omlims[0]+ind*dOmega),w_cb,dOmega) Rect.set_facecolor(plt.cm.bwr(icol[ind])) Rect.set_edgecolor(None) Rect.set_alpha(ialpha[ind]) ax1.add_artist(Rect) ax1.axis('scaled') ax1.set_xlim([0,w_cb])
def create_board_figure(pcb, bom_row, layer=pcbnew.F_Cu, invert_axis=False): qty, value, footpr, highlight_refs = bom_row plt.figure(figsize=(5.8, 8.2)) ax = plt.subplot("111", aspect="equal") color_pad1 = "lightgray" color_pad2 = "#AA0000" color_pad3 = "#CC4444" color_bbox1 = "None" color_bbox2 = "#E9AFAF" # get board edges (assuming rectangular, axis aligned pcb) edge_coords = [] for d in pcb.GetDrawings(): if (d.GetLayer() == pcbnew.Edge_Cuts): edge_coords.append(d.GetStart()) edge_coords.append(d.GetEnd()) edge_coords = np.asarray(edge_coords) * 1e-6 board_xmin, board_ymin = edge_coords.min(axis=0) board_xmax, board_ymax = edge_coords.max(axis=0) # draw board edges rct = Rectangle((board_xmin, board_ymin), board_xmax - board_xmin, board_ymax - board_ymin, angle=0) rct.set_color("None") rct.set_edgecolor("black") rct.set_linewidth(3) ax.add_patch(rct) # add title ax.text(board_xmin + .5 * (board_xmax - board_xmin), board_ymin - 0.5, "%dx %s, %s" % (qty, value, footpr), wrap=True, horizontalalignment='center', verticalalignment='bottom')\ # add ref list textsize = 12 refdes_text = ", ".join(highlight_refs) if len(refdes_text) > 200: # limit the size to prevent truncation textsize = 10 if len(refdes_text) > 500: # limit the size to prevent truncation textsize = 8 if len(refdes_text) > 1100: textsize = 6 ax.text(board_xmin + .5 * (board_xmax - board_xmin), board_ymax + 0.5, ", ".join(highlight_refs), wrap=True, horizontalalignment='center', verticalalignment='top', fontsize=textsize) # draw parts for m in pcb.GetModules(): if m.GetLayer() != layer: continue ref, center = m.GetReference(), np.asarray(m.GetCenter()) * 1e-6 highlight = ref in highlight_refs # bounding box mrect = m.GetFootprintRect() mrect_pos = np.asarray(mrect.GetPosition()) * 1e-6 mrect_size = np.asarray(mrect.GetSize()) * 1e-6 rct = Rectangle(mrect_pos, mrect_size[0], mrect_size[1]) rct.set_color(color_bbox2 if highlight else color_bbox1) rct.set_alpha(0.7) rct.set_zorder(-1) if highlight: rct.set_linewidth(.1) rct.set_edgecolor(color_pad2) ax.add_patch(rct) # center marker if highlight: plt.plot(center[0], center[1], ".", markersize=mrect_size.min() / 4, color=color_pad2) # plot pads for p in m.Pads(): pos = np.asarray(p.GetPosition()) * 1e-6 #additional scaling pads result in strange effects on pads made #from multiple pads - so I removed the * 0.9 size = np.asarray(p.GetSize()) * 1e-6 is_pin1 = p.GetPadName() == "1" or p.GetPadName() == "A1" shape = p.GetShape() offset = p.GetOffset() # TODO: check offset # pad rect angle = p.GetOrientation() * 0.1 cos, sin = np.cos(np.pi / 180. * angle), np.sin(np.pi / 180. * angle) dpos = np.dot([[cos, -sin], [sin, cos]], -.5 * size) if shape == pcbnew.PAD_SHAPE_RECT: rct = Rectangle(pos + dpos, size[0], size[1], angle=angle) elif shape == pcbnew.PAD_SHAPE_ROUNDRECT: # subtract 2x corner radius from pad size, as FancyBboxPatch draws a rounded rectangle around the specified rectangle pad = p.GetRoundRectCornerRadius() * 1e-6 # the bottom-left corner of the FancyBboxPatch is the inside rectangle so need to compensate with the corner radius corneroffset = np.asarray([pad, pad]) #draw rounded patch rct = FancyBboxPatch(pos + dpos + corneroffset, size[0] - 2 * pad, size[1] - 2 * pad, boxstyle=matplotlib.patches.BoxStyle( "Round", pad=pad)) #and rotate it xy = pos + dpos tfm = matplotlib.transforms.Affine2D().rotate_deg_around( xy[0], xy[1], angle) + ax.transData rct.set_transform(tfm) elif shape == pcbnew.PAD_SHAPE_OVAL: rct = Ellipse(pos, size[0], size[1], angle=angle) elif shape == pcbnew.PAD_SHAPE_CIRCLE: rct = Ellipse(pos, size[0], size[0], angle=angle) elif shape == pcbnew.PAD_SHAPE_TRAPEZOID: #draw trapezoid from scratch sx = size[0] sy = size[1] delta = p.GetDelta()[1] * 1e-6 xy = np.array([[(sx + delta) / 2, sy / 2], [(sx - delta) / 2, -sy / 2], [(-sx + delta) / 2, -sy / 2], [(-sx - delta) / 2, sy / 2]]) xy = xy + pos rct = Polygon(xy) #and rotate it xy = pos # TODO DEBUG: based on corrections made in ROUNDRECT code above, the angle should NOT be negative(might be bug). No use case so ignored for now tfm = matplotlib.transforms.Affine2D().rotate_deg_around( xy[0], xy[1], -angle) + ax.transData rct.set_transform(tfm) else: print("Unsupported pad shape: {0} ".format(shape)) continue rct.set_linewidth(0) rct.set_color(color_pad2 if highlight else color_pad1) rct.set_zorder(1) # highlight pin1 if highlight and is_pin1: rct.set_color(color_pad3) rct.set_linewidth(.1) rct.set_edgecolor(color_pad2) ax.add_patch(rct) plt.xlim(board_xmin, board_xmax) plt.ylim(board_ymax, board_ymin) if (invert_axis): plt.gca().invert_xaxis() plt.axis('off')
def draw_chiprep2(dm, cx, axi=0, fsel=None, in_image_bit=False, axi_color=0, bbox_bit=None, ell_alpha=None, ell_bit=None, xy_bit=None, color=None, qcm=None, **kwargs): ''' Draws a chip representation over an already drawn chip cx - the chiprep to draw. Managed by the chip manager axi - the axis index to draw it in #TODO: in_image_bit becomes data_coordinates in_image_bit - are the data coordinates image or rotated chip? raw the chip by itself or in its original image axi_color - use the color associated with axis index (used for ploting queries) --- Others are preference overloads bbox_bit - ell_alpha ell_bit xy_bit ell_color ''' # Allows display of cross database queries cm = dm.hs.cm if qcm is None else qcm # Grab Preferences xy_bit = dm.draw_prefs.points_bit if xy_bit is None else xy_bit ell_bit = dm.draw_prefs.ellipse_bit if ell_bit is None else ell_bit bbox_bit = dm.draw_prefs.bbox_bit if bbox_bit is None else bbox_bit ell_alpha = dm.draw_prefs.ellipse_alpha if ell_alpha is None else ell_alpha # Make sure alpha in range [0,1] if ell_alpha > 1: ell_alpha = 1.0 if ell_alpha < 0: ell_alpha = 0.0 # Get color from colormap or overloaded parameter if color is None: color = plt.get_cmap('hsv')(float(axi_color)/len(dm.ax_list))[0:3] if axi_color == 0: color = [color[0], color[1]+.5, color[2]] # Axis We are drawing to. ax = dm.ax_list[axi] T_data = ax.transData # data coordinates -> display coordinates # Data coordinates are chip coords if xy_bit or ell_bit or fsel != None: T_fpts = T_data if not in_image_bit else\ Affine2D(cm.cx2_T_chip2img(cx) ) + T_data fpts = cm.get_fpts(cx) if fsel is None: fsel = range(len(fpts)) # ---DEVHACK--- # Randomly sample the keypoints. (Except be sneaky) elif fsel == 'rand': # Get Relative Position minxy = fpts.min(0)[0:2] maxxy = fpts.max(0)[0:2] rel_pos = (fpts[:,0]-minxy[0])/(maxxy[0]-minxy[0]) to_zero = 1 - np.abs(rel_pos - .5)/.5 pdf = (to_zero / to_zero.sum()) # Transform Relative Position to Probabilities # making it more likely to pick a centerpoint fsel = np.random.choice(xrange(len(fpts)), size=88, replace=False, p=pdf) # ---/DEVHACK--- # Plot ellipses if ell_bit and len(fpts) > 0 and len(fsel) > 0: ells = dm._get_fpt_ell_collection(fpts[fsel,:], T_fpts, ell_alpha, color) ax.add_collection(ells) # Plot xy points if xy_bit and len(fpts) > 0 and len(fsel) > 0: ax.plot(fpts[fsel,0], fpts[fsel,1], 'o',\ markeredgecolor=color,\ markerfacecolor=color,\ transform=T_fpts,\ markersize=2) # === if bbox_bit: # Draw Bounding Rectangle in Image Coords [rx,ry,rw,rh] = cm.cx2_roi[cx] rxy = (rx,ry) # Convert to Chip Coords if needbe T_bbox = T_data if in_image_bit else\ Affine2D( np.linalg.inv(cm.cx2_T_chip2img(cx)) ) + T_data bbox = Rectangle(rxy,rw,rh,transform=T_bbox) # Visual Properties bbox.set_fill(False) bbox.set_edgecolor(color) ax.add_patch(bbox) # Draw Text Annotation cid = cm.cx2_cid[cx] name = cm.cx2_name(cx) # Lower the value to .2 for the background color and set alpha=.7 rgb_textFG = [1,1,1] hsv_textBG = colorsys.rgb_to_hsv(*color)[0:2]+(.2,) rgb_textBG = colorsys.hsv_to_rgb(*hsv_textBG)+(.7,) # Draw Orientation Backwards degrees = 0 if not in_image_bit else -cm.cx2_theta[cx]*180/np.pi txy = (0,rh) if not in_image_bit else (rx, ry+rh) chip_text = 'name='+name+'\n'+'cid='+str(cid) ax.text(txy[0]+1, txy[1]+1, chip_text, horizontalalignment ='left', verticalalignment ='top', transform =T_data, rotation =degrees, color =rgb_textFG, backgroundcolor =rgb_textBG) return fsel
#Block rect = Rectangle((XPT[0],YY*1000-H/2), width=W, height=H,alpha=1.0,fill=True,color=ColorB,linewidth=0) ax.add_patch(rect) # rect.set_edgecolor("black") else: #Silent rect = Rectangle((XPT[0],YY*1000-H/2), width=W, height=H,alpha=1.0,fill=True,color=ColorS,linewidth=0) ax.add_patch(rect) # rect.set_edgecolor("black") else: Rate=len(Node0)/2/Factor/MaxAP+1/2/Factor if Rate>1/Factor: Rate=1/Factor rect = Rectangle((XPT[0],YY*1000-H/2), width=W, height=H,alpha=1.0,fill=True,color=cmap(Rate),linewidth=0) ax.add_patch(rect) rect = Rectangle((XPT[0],-4-H/2), width=W, height=8+H,alpha=1.0,fill=False,linewidth=0.75) rect.set_edgecolor("black") ax.add_patch(rect) ax.axis('scaled') ax.set_frame_on(False) ax.xaxis.set_ticks_position('none') ax.set_ylabel('Axon distance from midline [mm]',fontsize=10) ax.tick_params(axis='x', pad=-10) plt.xticks([]) plt.yticks([-4,-3,-2,-1,0,1,2,3,4]) plt.show()
def create_board_figure(pcb, bom_row, layer=pcbnew.F_Cu): msg = "" unsupported_pads = [] qty, value, footpr, highlight_refs = bom_row # global ax plt.figure(figsize=(5.8, 8.2)) ax = plt.subplot("111", aspect="equal") color_pad1 = "lightgray" color_pad2 = "#AA0000" color_pad3 = "#CC4444" color_bbox1 = "None" color_bbox2 = "#E9AFAF" # get board edges (assuming rectangular, axis aligned pcb) edge_coords = [] for d in pcb.GetDrawings(): if (d.GetLayer() == pcbnew.Edge_Cuts): edge_coords.append(d.GetStart()) edge_coords.append(d.GetEnd()) edge_coords = np.asarray(edge_coords) * 1e-6 board_xmin, board_ymin = edge_coords.min(axis=0) board_xmax, board_ymax = edge_coords.max(axis=0) # draw board edges rct = Rectangle((board_xmin, board_ymin), board_xmax - board_xmin, board_ymax - board_ymin, angle=0) rct.set_color("None") rct.set_edgecolor("black") rct.set_linewidth(3) ax.add_patch(rct) # add title ax.text(board_xmin + .5 * (board_xmax - board_xmin), board_ymin - 0.5, "%dx %s, %s" % (qty, value, footpr), horizontalalignment='center', verticalalignment='bottom') # add ref list ax.text((board_xmax + board_xmin) * 0.5, board_ymax + 0.5, textwrap.fill(", ".join(highlight_refs), 60), horizontalalignment='center', verticalalignment='top') # draw parts for m in pcb.GetModules(): if m.GetLayer() != layer: continue ref, center = m.GetReference(), np.asarray(m.GetCenter()) * 1e-6 highlight = ref in highlight_refs # bounding box mrect = m.GetFootprintRect() mrect_pos = np.asarray(mrect.GetPosition()) * 1e-6 mrect_size = np.asarray(mrect.GetSize()) * 1e-6 rct = Rectangle(mrect_pos, mrect_size[0], mrect_size[1]) rct.set_color(color_bbox2 if highlight else color_bbox1) rct.set_zorder(-1) if highlight: rct.set_linewidth(.1) rct.set_edgecolor(color_pad2) ax.add_patch(rct) # center marker if highlight: plt.plot(center[0], center[1], ".", markersize=mrect_size.min(), color=color_pad2) # plot pads for p in m.Pads(): pos = np.asarray(p.GetPosition()) * 1e-6 size = np.asarray(p.GetSize()) * 1e-6 * .9 is_pin1 = p.GetPadName() == "1" or p.GetPadName() == "A1" shape = p.GetShape() offset = p.GetOffset() # TODO: check offset # pad rect angle = p.GetOrientation() * 0.1 cos, sin = np.cos(np.pi / 180. * angle), np.sin(np.pi / 180. * angle) dpos = np.dot([[cos, -sin], [sin, cos]], -.5 * size) if shape == 1: rct = Rectangle(pos + dpos, size[0], size[1], angle=angle) elif shape == 2: rct = Rectangle(pos + dpos, size[0], size[1], angle=angle) elif shape == 0: rct = Ellipse(pos, size[0], size[1], angle=angle) else: #todo: check if already printed this error #already_found_unsupported_shape = ref+p.GetPadName() in unsupported_pads #if !already_found_unsupported_shape: # unsupported_pads.append(ref+p.GetPadName()) print("Unsupported pad shape", shape) msg += "Unsupported pad shape " + str( shape) + " for " + ref + " at " + str( p.GetPosition().x) + ", " + str( p.GetPosition().y) + "\n" continue rct.set_linewidth(0) rct.set_color(color_pad2 if highlight else color_pad1) rct.set_zorder(1) # highlight pin1 if highlight and is_pin1: rct.set_color(color_pad3) rct.set_linewidth(.1) rct.set_edgecolor(color_pad2) ax.add_patch(rct) #checks for F.Cu layer - if not, plot is mirrored if m.GetLayer() == pcbnew.F_Cu: plt.xlim(board_xmin, board_xmax) plt.ylim(board_ymax, board_ymin) else: plt.xlim(board_xmax, board_xmin) plt.ylim(board_ymax, board_ymin) plt.axis('off') return msg
def draw_chiprep2( dm, cx, axi=0, fsel=None, in_image_bit=False, axi_color=0, bbox_bit=None, ell_alpha=None, ell_bit=None, xy_bit=None, color=None, qcm=None, **kwargs ): """ Draws a chip representation over an already drawn chip cx - the chiprep to draw. Managed by the chip manager axi - the axis index to draw it in #TODO: in_image_bit becomes data_coordinates in_image_bit - are the data coordinates image or rotated chip? raw the chip by itself or in its original image axi_color - use the color associated with axis index (used for ploting queries) --- Others are preference overloads bbox_bit - ell_alpha ell_bit xy_bit ell_color """ # Allows display of cross database queries cm = dm.hs.cm if qcm is None else qcm # Grab Preferences xy_bit = dm.draw_prefs.points_bit if xy_bit is None else xy_bit ell_bit = dm.draw_prefs.ellipse_bit if ell_bit is None else ell_bit bbox_bit = dm.draw_prefs.bbox_bit if bbox_bit is None else bbox_bit ell_alpha = dm.draw_prefs.ellipse_alpha if ell_alpha is None else ell_alpha # Make sure alpha in range [0,1] if ell_alpha > 1: ell_alpha = 1.0 if ell_alpha < 0: ell_alpha = 0.0 # Get color from colormap or overloaded parameter if color is None: color = plt.get_cmap("hsv")(float(axi_color) / len(dm.ax_list))[0:3] if axi_color == 0: color = [color[0], color[1] + 0.5, color[2]] # Axis We are drawing to. ax = dm.ax_list[axi] T_data = ax.transData # data coordinates -> display coordinates # Data coordinates are chip coords if xy_bit or ell_bit or fsel != None: T_fpts = T_data if not in_image_bit else Affine2D(cm.cx2_T_chip2img(cx)) + T_data fpts = cm.get_fpts(cx) if fsel is None: fsel = range(len(fpts)) # ---DEVHACK--- # Randomly sample the keypoints. (Except be sneaky) elif fsel == "rand": # Get Relative Position minxy = fpts.min(0)[0:2] maxxy = fpts.max(0)[0:2] rel_pos = (fpts[:, 0] - minxy[0]) / (maxxy[0] - minxy[0]) to_zero = 1 - np.abs(rel_pos - 0.5) / 0.5 pdf = to_zero / to_zero.sum() # Transform Relative Position to Probabilities # making it more likely to pick a centerpoint fsel = np.random.choice(xrange(len(fpts)), size=88, replace=False, p=pdf) # ---/DEVHACK--- # Plot ellipses if ell_bit and len(fpts) > 0 and len(fsel) > 0: ells = dm._get_fpt_ell_collection(fpts[fsel, :], T_fpts, ell_alpha, color) ax.add_collection(ells) # Plot xy points if xy_bit and len(fpts) > 0 and len(fsel) > 0: ax.plot( fpts[fsel, 0], fpts[fsel, 1], "o", markeredgecolor=color, markerfacecolor=color, transform=T_fpts, markersize=2, ) # === if bbox_bit: # Draw Bounding Rectangle in Image Coords [rx, ry, rw, rh] = cm.cx2_roi[cx] rxy = (rx, ry) # Convert to Chip Coords if needbe T_bbox = T_data if in_image_bit else Affine2D(np.linalg.inv(cm.cx2_T_chip2img(cx))) + T_data bbox = Rectangle(rxy, rw, rh, transform=T_bbox) # Visual Properties bbox.set_fill(False) bbox.set_edgecolor(color) ax.add_patch(bbox) # Draw Text Annotation cid = cm.cx2_cid[cx] name = cm.cx2_name(cx) # Lower the value to .2 for the background color and set alpha=.7 rgb_textFG = [1, 1, 1] hsv_textBG = colorsys.rgb_to_hsv(*color)[0:2] + (0.2,) rgb_textBG = colorsys.hsv_to_rgb(*hsv_textBG) + (0.7,) # Draw Orientation Backwards degrees = 0 if not in_image_bit else -cm.cx2_theta[cx] * 180 / np.pi txy = (0, rh) if not in_image_bit else (rx, ry + rh) chip_text = "name=" + name + "\n" + "cid=" + str(cid) ax.text( txy[0] + 1, txy[1] + 1, chip_text, horizontalalignment="left", verticalalignment="top", transform=T_data, rotation=degrees, color=rgb_textFG, backgroundcolor=rgb_textBG, ) return fsel