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 bounding_box(self, data, ax, label, bBoundingBoxes, bLabels): """Draw bounding box around data.""" data = np.array(data) width = max(data[:, 0]) - min(data[:, 0]) height = max(data[:, 1]) - min(data[:, 1]) r = Rectangle((min(data[:, 0]), min(data[:, 1])), width, height) if bBoundingBoxes: ax.add_artist(r) r.set_clip_box(ax.bbox) r.set_alpha(0.1) r.set_facecolor((0.5, 0.5, 0.5)) if bLabels: ax.annotate(label, xy=(min(data[:, 0]), max(data[:, 1])), xytext=(0, 0), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc=(0.5, 0.5, 0.5), alpha=0.1))
def demo_draw(): ax = init_figure(-15, 15, -15, 15) c = array([[5], [0]]) e = Ellipse(xy=c, width=13.0, height=2.0, angle=45) ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(0.9) e.set_facecolor(array([0.7, 0.3, 0.6])) rect = Rectangle((1, 1), width=5, height=3) rect.set_facecolor(array([0.4, 0.3, 0.6])) ax.add_patch(rect) pause(0.2) draw_tank(array([[-7], [5], [1]])) draw_tank(array([[-7], [5], [1]]), 'red', 0.2) draw_car(array([[1], [2], [3], [4], [0.5]]), 'blue', 3) P = array([[5, -3], [9, -10], [7, -4], [7, -6]]) draw_polygon(ax, P, 'green') draw_disk(ax, array([[-8], [-8]]), 2, "blue") draw_arc(array([[0], [5]]), array([[4], [6]]), 2, 'red') show( ) # only at the end. Otherwize, it closes the figure in a terminal mode
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 demo_draw(): fig = figure(0) ax = fig.add_subplot(111, aspect='equal') ax.set_xlim(-10, 10) ax.set_ylim(-10, 10) c = array([[5], [0]]) e = Ellipse(xy=c, width=13.0, height=2.0, angle=45) ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(0.9) e.set_facecolor(array([0.7, 0.3, 0.6])) rect = Rectangle((1, 1), width=5, height=3) rect.set_facecolor(array([0.4, 0.3, 0.6])) ax.add_patch(rect) pause(0.2) draw_tank(array([[-7], [5], [1]])) draw_tank(array([[-7], [5], [1]]), 'red', 0.2) draw_car(array([[1], [2], [3], [4], [0.5]])) c = array([[-2], [-3]]) G = array([[2, -1], [-1, 4]]) draw_ellipse(c, G, 0.9, ax, [0.8, 0.8, 1]) P = array([[5, -3], [9, -10], [7, -4], [7, -6]]) draw_polygon(P, ax, 'green') draw_disk(array([[-8], [-8]]), 2, ax, "blue") draw_arc(array([[0], [5]]), array([[4], [6]]), 2, 'red') show( ) # only at the end. Otherwize, it closes the figure in a terminal mode
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 draw_box(x1, x2, y1, y2, ax, col): c = array([[x1], [y1]]) rect = Rectangle(c, width=x2 - x1, height=y2 - y1, angle=0) rect.set_facecolor(array([0.4, 0.3, 0.6])) ax.add_patch(rect) rect.set_clip_box(ax.bbox) rect.set_alpha(0.7) rect.set_facecolor(col)
def __init__(self, x, y, dx, dy, border_tol=0.1, resize=True, plotview=None, **opts): shape = Rectangle((float(x),float(y)), float(dx), float(dy), **opts) if 'linewidth' not in opts: shape.set_linewidth(1.0) if 'facecolor' not in opts: shape.set_facecolor('r') super(NXrectangle, self).__init__(shape, border_tol, resize, plotview) self.shape.set_label('Rectangle') self.rectangle = self.shape
def legend(self, ax): handles = [] labels = [] for name, color in self.pal.items(): p = Rectangle((0, 0), 1, 1) p.set_facecolor(color) handles.append(p) labels.append(name) ax.legend(handles, labels, loc="best")
def draw_rectangle(self,xs,ys,alpha=0.2,color='g'): xy = (min(xs),min(ys)) width = np.abs(np.diff(xs)) height = np.abs(np.diff(ys)) re = Rectangle(xy, width, height, angle=0.0) ax = self.axs[0] ax.add_artist(re) re.set_alpha(alpha=alpha) re.set_facecolor(color) return re
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 create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): p1 = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) p2 = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) self.update_prop(p1, orig_handle, legend) self.update_prop(p2, orig_handle, legend) p2.set_facecolor('none') p1.set_transform(trans) p2.set_transform(trans) return [p1,p2]
def draw_rectangle(self, lower, upper, node): r = Rectangle(lower, upper[0] - lower[0], upper[1]-lower[1], edgecolor='k', facecolor = (0,0,0)) self.ax.add_patch(r) if node.is_leaf(): rx, ry = r.get_xy() cx = rx + r.get_width()/2.0 cy = ry + r.get_height()/2.0 r.set_facecolor( node.get_colour()) self.ax.annotate(node.get_weight(), (cx, cy), color=(0,0,0), fontsize = 10, ha='center', va='center') print node.name, rx, ry, cx, cy
def colors_vis(ax): bars = range(STIMULATION_FRAME,STIMULATION_FRAME+12) _pc = [] for i,w in enumerate(bars): r = Rectangle((0,i),1,1) r.set_facecolor(colors[i]) _pc.append(r) for w in _pc: ax.add_patch(w) ax.set_yticks([xx+0.5 for xx in range(len(_pc))]) ax.set_yticklabels(list(bars)) ax.set_ylabel('Frame color code',fontsize=14) return
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 drawTables(coords, tables): lw = 2 c = [0, 0, 0] tables_color = [[0.2, 0.3, 0.7], [0.9, 0.6, 0.32], [1, 0, 0], [0.9, 0.6, 0.32]] colors = [] xs = [coords[0], coords[1], coords[1], coords[0], coords[0]] ys = [coords[3], coords[3], coords[2], coords[2], coords[3]] plt.plot(xs, ys, color=c, linewidth=lw) plt.axis(coords) ax = plt.gca() patches = [] count = 0 margin = 0.5 text_margin = 0.15 for table in tables: x = table.get_feature("x").value - margin y = table.get_feature("y").value - margin # plt.plot(r*np.cos(an) + x, r*np.sin(an) + y, color = c[count]) # ray = agents[i, :2] + np.asarray([(agents[i, 2]) * np.cos(agents[i, 3]), (agents[i, 2]) * np.sin(agents[i, 3])]) # plt.plot([agents[i, 0], ray[0]], [agents[i, 1], ray[1]], color = c[i] ) rect = Rectangle( (x, y), 1, 1) # facecolor doesnt work with collection?, facecolor=c[i]) label = ax.annotate("T" + str(table.id), xy=(table.get_feature("x").value, table.get_feature("y").value - text_margin), fontsize=15, ha="center") rect.set_facecolor(tables_color[int(table.id)]) colors.append(tables_color[int(table.id)]) patches.append(rect) count += 1 p = PatchCollection(patches, alpha=0.4, facecolor=colors) ax.add_collection(p)
def boundingBox(self, data, ax, label, bBoundingBoxes, bLabels): ''' Draw bounding box around data.''' data = np.array(data) width = max(data[:,0]) - min(data[:,0]) height = max(data[:,1]) - min(data[:,1]) r = Rectangle((min(data[:,0]), min(data[:,1])), width, height) if bBoundingBoxes: ax.add_artist(r) r.set_clip_box(ax.bbox) r.set_alpha(0.1) r.set_facecolor((0.5, 0.5, 0.5)) if bLabels: ax.annotate(label, xy = (min(data[:,0]), max(data[:,1])), xytext = (0, 0), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = (0.5, 0.5, 0.5), alpha = 0.1))
def visualize_generation(self, generation): """ Draw each ab combination color and size coded :param generation: :param ax: :return: """ fig, ax = plt.subplots() # ax.clear() for ind in range(len(self.ga_solver.population[generation])): child = self.ga_solver.population[generation][ind] xy = self._ab_to_xy(child) rect = Rectangle(xy=xy, width=0.5, height=0.5, angle=90) ax.add_artist(rect) rect.set_clip_box(ax.bbox) # alpha = float(child[3]) / ANTIBODY_CNT # rgb = [float(child[0])/ANTIBODY_CNT, float(child[1])/ANTIBODY_CNT, float(child[2])/ANTIBODY_CNT/ ANTIBODY_CNT] # # rect.set_alpha(alpha) # rect.set_facecolor(rgb) fitness = self.ga_solver.get_fitness_value(child) if fitness > 0.5: rect.set_facecolor('r') else: rect.set_facecolor('b') rect.set_width(fitness * 100) rect.set_height(fitness * 100) ax.set_xlim( 0, self.ga_solver.antibody_cnt * self.ga_solver.antibody_cnt + 10) ax.set_ylim( 0, self.ga_solver.antibody_cnt * self.ga_solver.antibody_cnt + 10) plt.show() plt.pause(1) plt.close()
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
def visualise(cls, sensor, sL=None, show_sun=False, sides=True, interactive=False, colormap=None, scale=[0, 1], title=None): """ :param sensor: :type sensor: CompassSensor :return: """ import matplotlib.pyplot as plt from matplotlib.patches import Ellipse, Rectangle from matplotlib.cm import get_cmap import matplotlib as mpl if interactive: plt.ion() if colormap is not None: get_colour = lambda x: get_cmap(colormap)(x) else: get_colour = lambda x: x * np.array([.5, .5, 1.]) xyz = sph2vec(np.pi / 2 - sensor.theta_local, np.pi + sensor.phi_local, sensor.R_c) xyz[0] *= -1 lat, lon = hp.Rotator(rot=(np.rad2deg(-sensor.yaw), np.rad2deg(-sensor.pitch), np.rad2deg(-sensor.roll)))( sensor.sky.lat, np.pi - sensor.sky.lon) xyz_sun = sph2vec(np.pi / 2 - lat, np.pi + lon, sensor.R_c) xyz_sun[0] *= -1 if sides: figsize = (10, 10) else: if colormap is None or scale is None: figsize = (5, 5) else: figsize = (5.05, 5.05) plt.figure("Sensor Design" if title is None else title, figsize=figsize) # top view if sides: ax_t = plt.subplot2grid((4, 4), (1, 1), colspan=2, rowspan=2, aspect="equal", adjustable='box-forced') else: if colormap is not None and scale is not None: ax_t = plt.subplot2grid((10, 10), (0, 0), colspan=9, rowspan=9, aspect="equal", adjustable='box-forced') else: ax_t = plt.subplot(111) outline = Ellipse(xy=np.zeros(2), width=2 * sensor.R_c, height=2 * sensor.R_c) sensor_outline = Ellipse(xy=np.zeros(2), width=2 * sensor.alpha + 2 * sensor.R_l, height=2 * sensor.alpha + 2 * sensor.R_l) ax_t.add_artist(outline) outline.set_clip_box(ax_t.bbox) outline.set_alpha(.2) outline.set_facecolor("grey") ax_t.add_artist(sensor_outline) sensor_outline.set_clip_box(ax_t.bbox) sensor_outline.set_alpha(.5) sensor_outline.set_facecolor("grey") stheta, sphi = sensor.theta_local, np.pi + sensor.phi_local sL = sL if sL is not None else sensor.L if sensor.mode == "event": sL = np.clip(1. * sL + .5, 0., 1.) for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL): lens = Ellipse(xy=[x, y], width=1.5 * sensor.r_l, height=1.5 * np.cos(th) * sensor.r_l, angle=np.rad2deg(ph)) ax_t.add_artist(lens) lens.set_clip_box(ax_t.bbox) lens.set_facecolor(get_colour(np.asscalar(L))) if show_sun: ax_t.plot(xyz_sun[0], xyz_sun[1], 'ro', markersize=22) ax_t.set_xlim(-sensor.R_c - 2, sensor.R_c + 2) ax_t.set_ylim(-sensor.R_c - 2, sensor.R_c + 2) ax_t.set_xticklabels([]) ax_t.set_yticklabels([]) if sides: # side view #1 (x, z) ax = plt.subplot2grid((4, 4), (0, 1), colspan=2, aspect="equal", adjustable='box-forced', sharex=ax_t) outline = Ellipse(xy=np.zeros(2), width=2 * sensor.R_c, height=2 * sensor.R_c) fade_one = Rectangle(xy=[-sensor.R_c, -sensor.R_c], width=2 * sensor.R_c, height=2 * sensor.R_c - sensor.height - sensor.R_l) ax.add_artist(outline) outline.set_clip_box(ax.bbox) outline.set_alpha(.5) outline.set_facecolor("grey") ax.add_artist(fade_one) fade_one.set_clip_box(ax.bbox) fade_one.set_alpha(.6) fade_one.set_facecolor("white") for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL): if y > 0: continue lens = Ellipse(xy=[x, z], width=1.5 * sensor.r_l, height=np.sin(-y / sensor.R_c) * 1.5 * sensor.r_l, angle=np.rad2deg(np.arcsin(-x / sensor.R_c))) ax.add_artist(lens) lens.set_clip_box(ax.bbox) lens.set_facecolor(get_colour(L)) ax.set_xlim(-sensor.R_c - 2, sensor.R_c + 2) ax.set_ylim(0, sensor.R_c + 2) ax.set_xticks([]) ax.set_yticks([]) # side view #2 (-x, z) ax = plt.subplot2grid((4, 4), (3, 1), colspan=2, aspect="equal", adjustable='box-forced', sharex=ax_t) outline = Ellipse(xy=np.zeros(2), width=2 * sensor.R_c, height=2 * sensor.R_c) fade_one = Rectangle( xy=[-sensor.R_c, -sensor.R_c + sensor.height + sensor.R_l], width=2 * sensor.R_c, height=2 * sensor.R_c - sensor.height - sensor.R_l) ax.add_artist(outline) outline.set_clip_box(ax.bbox) outline.set_alpha(.5) outline.set_facecolor("grey") ax.add_artist(fade_one) fade_one.set_clip_box(ax.bbox) fade_one.set_alpha(.6) fade_one.set_facecolor("white") for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL): if y < 0: continue lens = Ellipse(xy=[x, -z], width=1.5 * sensor.r_l, height=np.sin(-y / sensor.R_c) * 1.5 * sensor.r_l, angle=np.rad2deg(np.arcsin(x / sensor.R_c))) ax.add_artist(lens) lens.set_clip_box(ax.bbox) lens.set_facecolor(get_colour(L)) ax.set_xlim(-sensor.R_c - 2, sensor.R_c + 2) ax.set_ylim(-sensor.R_c - 2, 0) ax.set_yticks([]) # side view #3 (y, z) ax = plt.subplot2grid((4, 4), (1, 3), rowspan=2, aspect="equal", adjustable='box-forced', sharey=ax_t) outline = Ellipse(xy=np.zeros(2), width=2 * sensor.R_c, height=2 * sensor.R_c) fade_one = Rectangle(xy=[-sensor.R_c, -sensor.R_c], width=2 * sensor.R_c - sensor.height - sensor.R_l, height=2 * sensor.R_c) ax.add_artist(outline) outline.set_clip_box(ax.bbox) outline.set_alpha(.5) outline.set_facecolor("grey") ax.add_artist(fade_one) fade_one.set_clip_box(ax.bbox) fade_one.set_alpha(.6) fade_one.set_facecolor("white") for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL): if x > 0: continue lens = Ellipse( xy=[z, y], width=1.5 * sensor.r_l, height=np.sin(-x / sensor.R_c) * 1.5 * sensor.r_l, angle=np.rad2deg(np.arcsin(y / sensor.R_c)) + 90) ax.add_artist(lens) lens.set_clip_box(ax.bbox) lens.set_facecolor(get_colour(L)) ax.set_ylim(-sensor.R_c - 2, sensor.R_c + 2) ax.set_xlim(0, sensor.R_c + 2) ax.set_yticks([]) ax.set_xticks([]) # side view #4 (-y, z) ax = plt.subplot2grid((4, 4), (1, 0), rowspan=2, aspect="equal", adjustable='box-forced', sharey=ax_t) outline = Ellipse(xy=np.zeros(2), width=2 * sensor.R_c, height=2 * sensor.R_c) fade_one = Rectangle( xy=[-sensor.R_c + sensor.height + sensor.R_l, -sensor.R_c], width=2 * sensor.R_c - sensor.height - sensor.R_l, height=2 * sensor.R_c) ax.add_artist(outline) outline.set_clip_box(ax.bbox) outline.set_alpha(.5) outline.set_facecolor("grey") ax.add_artist(fade_one) fade_one.set_clip_box(ax.bbox) fade_one.set_alpha(.6) fade_one.set_facecolor("white") for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL): if x < 0: continue lens = Ellipse( xy=[-z, y], width=1.5 * sensor.r_l, height=np.sin(-x / sensor.R_c) * 1.5 * sensor.r_l, angle=np.rad2deg(np.arcsin(-y / sensor.R_c)) - 90) ax.add_artist(lens) lens.set_clip_box(ax.bbox) lens.set_facecolor(get_colour(L)) ax.set_ylim(-sensor.R_c - 2, sensor.R_c + 2) ax.set_xlim(-sensor.R_c - 2, 0) ax.set_xticks([]) else: plt.axis('off') if colormap is not None and not sides and scale is not None: ax = plt.subplot2grid((10, 10), (9, 9), aspect="equal", adjustable='box-forced', projection='polar') ax._direction = 2 * np.pi ax.set_theta_zero_location("N") # quant_steps = 360 cb = mpl.colorbar.ColorbarBase(ax, cmap=get_cmap(colormap), norm=mpl.colors.Normalize( 0.0, 2 * np.pi), orientation='horizontal', ticks=np.linspace(0, 2 * np.pi, 4, endpoint=False)) cb.outline.set_visible(False) # cb.ax.set_xticks([0, np.pi/6, np.pi/3, np.pi/2, 2*np.pi/3, 5*np.pi/6, np.pi]) cb.ax.set_xticklabels( np.linspace(scale[0], scale[1], 4, endpoint=False)) cb.ax.tick_params(pad=1, labelsize=8) plt.tight_layout(pad=0.) if interactive: plt.draw() plt.pause(.1) else: plt.show()
dOmega = Omega[1]-Omega[0] 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')
def crust_box(self,ord): # Dashed lines to show zoom plot.plot([0.01,0.408],[0.31,0.5],color='white', ls='--',lw=1.5,zorder=ord) plot.plot([0.51,0.412],[0.31,0.5],color='white', ls='--',lw=1.5,zorder=ord) # Boxes to provide background box_bkgd1=Rectangle((0.01,0.01),0.5,0.3,zorder=ord, color='white',lw=1.5) self.ax.add_artist(box_bkgd1) box_bkgd2=Rectangle((0.41,0.01),0.1,0.3,zorder=ord,lw=0) box_bkgd2.set_facecolor(self.core_color) self.ax.add_artist(box_bkgd2) box_bkgd3=Rectangle((0.01,0.01),0.2,0.3,zorder=ord,lw=0) box_bkgd3.set_facecolor(self.crust_color) self.ax.add_artist(box_bkgd3) box_bkgd4=Rectangle((0.21,0.01),0.2,0.3,zorder=ord,lw=0) box_bkgd4.set_facecolor(self.neutron_color) self.ax.add_artist(box_bkgd4) # Nuclei for j in range(0,20): shift=rand()*0.02 if j%2==0: shift=shift+0.15/float(j+2) for i in range(0,j+2): y=0.3*float(i)/float(j+2)+0.01+shift if y>0.30: y=0.30 nuc1=Ellipse((0.02+float(j)*0.02,y), 0.01,0.01,zorder=ord+1,lw=0) nuc1.set_facecolor(self.core_color) self.ax.add_artist(nuc1) # Pasta for i in range(0,60): y=0.3*float(i)/60.0 if (y<0.03): y=0.03 pasta1=Ellipse((0.40-0.1*rand()*rand(),y), 0.01,0.04,angle=rand()*360,zorder=ord+1,lw=0) pasta1.set_facecolor(self.core_color) self.ax.add_artist(pasta1) # Thinner pasta for i in range(0,20): y=0.3*float(i)/20.0 if (y<0.04): y=0.04 pasta2=Ellipse((0.415-0.04*rand()*rand(),y), 0.01,0.06,angle=rand()*60-30,zorder=ord+1,lw=0) pasta2.set_facecolor(self.core_color) self.ax.add_artist(pasta2) # Labels self.ax.text(0.05,0.12,'Outer',fontsize=self.font_scale*0.8, color='black', rotation='90',va='center',ha='center',zorder=ord+2, bbox=dict(facecolor=self.crust_color,lw=0)) self.ax.text(0.09,0.12,'Crust',fontsize=self.font_scale*0.8, color='black', rotation='90',va='center',ha='center',zorder=ord+2, bbox=dict(facecolor=self.crust_color,lw=0)) self.ax.text(0.21,0.12,'neutron drip',fontsize=self.font_scale*0.6,color='black', rotation='90',va='center',ha='center',zorder=ord+2, bbox=dict(facecolor=self.crust_color,lw=0)) self.ax.text(0.25,0.12,'Inner',fontsize=self.font_scale*0.8, color='black', rotation='90',va='center',ha='center',zorder=ord+2, bbox=dict(facecolor=self.neutron_color,lw=0)) self.ax.text(0.29,0.12,'Crust',fontsize=self.font_scale*0.8, color='black', rotation='90',va='center',ha='center',zorder=ord+2, bbox=dict(facecolor=self.neutron_color,lw=0)) self.ax.text(0.38,0.12,'Pasta',fontsize=self.font_scale*0.8, color='black', rotation='90',va='center',ha='center',zorder=ord+2, bbox=dict(facecolor=self.core_color,lw=0)) self.ax.text(0.45,0.12,'Core',fontsize=self.font_scale*0.8, color='black', rotation='90',va='center',ha='center',zorder=ord+2) # Density labels self.ax.text(0.08,0.24,'g/cm$^{3}$:',fontsize=self.font_scale*0.8, color='black', va='bottom',ha='center',zorder=ord+2, bbox=dict(facecolor=self.crust_color,lw=0)) self.ax.text(0.18,0.25,'$10^{11}$',fontsize=self.font_scale*0.8, color='black', va='bottom',ha='center',zorder=ord+2, bbox=dict(facecolor=self.crust_color,lw=0)) self.ax.text(0.39,0.25,'$10^{14}$',fontsize=self.font_scale*0.8, color='black', va='bottom',ha='center',zorder=ord+2, bbox=dict(facecolor=self.core_color,lw=0)) # Crust thickness label self.ax.text(0.26,0.335, '$R_{\mathrm{crust}}=0.4-2.0~\mathrm{km}$', fontsize=self.font_scale*0.8,color=self.text_color, va='center',ha='center',zorder=13, bbox=dict(facecolor=self.bkgd_color,lw=0))
class Zoom(object): def __init__(self): self.is_pressed = False self.x0 = 0.0 self.y0 = 0.0 self.x1 = 0.0 self.y1 = 0.0 def zoom_init(self, x, y): graph = Figure(figsize=(5,4), dpi=100) self.ax = graph.add_subplot(111) self.rect = Rectangle((0,0),0,0) self.ax.add_patch(self.rect) self.ax.plot(x, y) canvas = FigureCanvasTkAgg(graph, master=RightFrame) canvas.show() print(x) print(y) canvas.get_tk_widget().grid(column=2, row=1, rowspan=2, sticky=(N, S, E, W)) self.aid = graph.canvas.mpl_connect('button_press_event', self.on_press) self.bid = graph.canvas.mpl_connect('button_release_event', self.on_release) self.cid = graph.canvas.mpl_connect('motion_notify_event', self.on_motion) def on_press(self, event): self.is_pressed = True if event.xdata is not None and event.ydata is not None: self.x0, self.y0 = event.xdata, event.ydata self.rect.set_width(0) self.rect.set_height(0) self.rect.set_xy((self.x0, self.y0)) self.ax.figure.canvas.draw() self.rect.set_facecolor('red') self.rect.set_linestyle('dashed') def on_motion(self, event): if self.is_pressed: if event.xdata is not None and event.ydata is not None: self.x1, self.y1 = event.xdata, 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)) self.ax.figure.canvas.draw() def on_release(self, event): self.is_pressed = False RightFrame.config(cursor="arrow") self.rect.set_facecolor('blue') self.rect.set_linestyle('solid') if self.x0 > self.x1: if self.y0 > self.y1: self.minX = self.x1 self.maxX = self.x0 self.minY = self.y1 self.maxY = self.y0 else: self.minX = self.x1 self.maxX = self.x0 self.minY = self.y0 self.maxY = self.y1 if self.x0 < self.x1: if self.y0 < self.y1: self.minX = self.x0 self.maxX = self.x1 self.minY = self.y0 self.maxY = self.y1 else: self.minX = self.x0 self.maxX = self.x1 self.minY = self.y1 self.maxY = self.y0 global minX, minY, maxX, maxY minX = self.minX minY = self.minY maxX = self.maxX maxY = self.maxY graph = Figure(figsize=(5,4), dpi=100) self.ax = graph.add_subplot(111) self.ax.set_xlim(self.minX, self.maxX) self.ax.set_ylim(self.minY, self.maxY) self.ax.plot(x, y) canvas = FigureCanvasTkAgg(graph, master=RightFrame) canvas.show() canvas.get_tk_widget().grid(column=2, row=1, rowspan=2, sticky=(N, S, E, W))
def bkgd(self): # Black background main_bkgd=Rectangle((0,0),1,1) main_bkgd.set_facecolor(self.bkgd_color) self.ax.add_artist(main_bkgd)
print >> sys.stderr, "Number of reflectance and image points should be equal." small = reduce(min, depths, depths[0]) depths = map(lambda f: f - small, depths) start = x[0] x = map(lambda f: f - start, x) fig = plt.figure() g = fig.add_subplot(3, 1, 1) g.plot(x, depths) g.set_xlim(x[0], x[len(x) - 1]) ref = fig.add_subplot(3, 1, 2) for i in xrange(len(reflectance)): e = Rectangle(xy=(i, 0), width=1, height=1, edgecolor='none') r = min(reflectance[i], 1) e.set_facecolor([r, r, r]) ref.add_artist(e) ref.set_frame_on(False) ref.get_xaxis().set_visible(False) ref.get_yaxis().set_visible(False) ref.set_xlim(0, len(reflectance)) ref.set_ylim(0, 1) ref = fig.add_subplot(3, 1, 3) for i in xrange(len(image)): e = Rectangle(xy=(i, 0), width=1, height=1, edgecolor='none') e.set_facecolor([image[i], image[i], image[i]]) ref.add_artist(e) ref.set_frame_on(False)
print >> sys.stderr, "Number of reflectance and image points should be equal." small = reduce(min, depths, depths[0]) depths = map(lambda f: f - small, depths) start = x[0] x = map(lambda f: f - start, x) fig = plt.figure() g = fig.add_subplot(3, 1, 1) g.plot(x, depths) g.set_xlim(x[0], x[len(x)-1]) ref = fig.add_subplot(3, 1, 2 ) for i in xrange(len(reflectance)): e = Rectangle(xy=(i,0), width=1, height=1, edgecolor='none') r = min(reflectance[i], 1) e.set_facecolor([r, r, r]) ref.add_artist(e) ref.set_frame_on(False) ref.get_xaxis().set_visible(False) ref.get_yaxis().set_visible(False) ref.set_xlim(0, len(reflectance)) ref.set_ylim(0, 1) ref = fig.add_subplot(3, 1, 3 ) for i in xrange(len(image)): e = Rectangle(xy=(i,0), width=1, height=1, edgecolor='none') e.set_facecolor([image[i], image[i], image[i]]) ref.add_artist(e) ref.set_frame_on(False)
offset = mne_corners[-1] - np.array( [mne_clip.get_extents().size[0] / 2., -dims[1]]) - tagline_offset_fudge tag_clip = Path(offset + vert * mult, tag_path.codes) tag_patch = PathPatch(tag_clip, facecolor='k', edgecolor='none', zorder=10) ax.add_patch(tag_patch) yl = ax.get_ylim() yy = np.max([tag_clip.vertices.max(0)[-1], tag_clip.vertices.min(0)[-1]]) ax.set_ylim(np.ceil(yy), yl[-1]) # only save actual image extent plus a bit of padding plt.draw() static_dir = op.join(op.dirname(__file__), '..', 'doc', '_static') assert op.isdir(static_dir) plt.savefig(op.join(static_dir, 'mne_logo.svg'), transparent=True) tag_patch.set_facecolor('w') rect.set_facecolor('0.5') plt.savefig(op.join(static_dir, 'mne_logo_dark.svg'), transparent=True) tag_patch.set_facecolor('k') rect.set_facecolor('w') # modify to make the splash screen data_dir = op.join(op.dirname(__file__), '..', 'mne', 'icons') ax.patches[-1].set_facecolor('w') for coll in list(ax.collections): coll.remove() bounds = np.array( [[mne_path.vertices[:, ii].min(), mne_path.vertices[:, ii].max()] for ii in range(2)]) bounds *= (plot_dims / dims) xy = np.mean(bounds, axis=1) - [100, 0] r = np.diff(bounds, axis=1).max() * 1.2
def plot_2d_map(self, ax, barriers: bool = True, barrier_mode: str = 'filled'): r""" Plots the drunkard's map onto an already existing matplotlib axis. One can select whether to draw barriers and if barriers should be drawn, whether they have a 'filled' face or be 'hollow' with just the border being colored. Parameters ---------- ax : matplotlib axis The axis. barriers : bool, default=True Whether to draw the barriers. barrier_mode : str, default='filled' How to draw barriers - can be one of 'filled' and 'hollow'. Returns ------- handles, labels Handles and labels for a matplotlib legend. """ import numpy as np from matplotlib.patches import Rectangle valid_barrier_modes = ('filled', 'hollow') if barrier_mode not in valid_barrier_modes: raise ValueError(f"Barrier mode '{barrier_mode}' not supported, valid modes are {valid_barrier_modes}.") ax.scatter(*self.home_location.T, marker='*', label='Home', c='red', s=150, zorder=5) ax.scatter(*self.bar_location.T, marker='*', label='Bar', c='orange', s=150, zorder=5) ax.set_xticks(np.arange(10)) ax.set_yticks(np.arange(10)) ax.set_xlabel('coordinate x') ax.set_ylabel('coordinate y') rect = None for state in range(self.n_states): coord = self.state_to_coordinate(state) if self._is_home_or_bar_coord(coord): ax.add_patch(Rectangle((coord[0] - .5, coord[1] - .5), 1., 1., alpha=.3, color='green')) elif barriers and coord in self.barriers: barrier_ix = self.barriers.index(coord) weight = self.barrier_weights[barrier_ix] if weight is None: rect = Rectangle((coord[0] - .5, coord[1] - .5), 1., 1., alpha=.5, color='red', lw=3.) if barrier_mode == 'hollow': rect.set_facecolor('none') ax.add_patch(rect) else: rect = Rectangle((coord[0] - .5, coord[1] - .5), 1., 1., alpha=.2, color='red', lw=3.) if barrier_mode == 'hollow': rect.set_facecolor('none') ax.add_patch(rect) for grid_point in np.arange(-.5, self.grid_size[0] + .5, 1): ax.axhline(grid_point, linestyle='-', color='grey', lw=.5) for grid_point in np.arange(-.5, self.grid_size[1] + .5, 1): ax.axvline(grid_point, linestyle='-', color='grey', lw=.5) handles, labels = ax.get_legend_handles_labels() if rect is not None: handles.append(rect) labels.append("Barrier") ax.set_xlim([-.5, self.grid_size[0] - .5]) ax.set_ylim([-.5, self.grid_size[1] - .5]) return handles, labels
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 crust_box(self, ord): # Dashed lines to show zoom plot.plot([0.01, 0.408], [0.31, 0.5], color='white', ls='--', lw=1.5, zorder=ord) plot.plot([0.51, 0.412], [0.31, 0.5], color='white', ls='--', lw=1.5, zorder=ord) # Boxes to provide background box_bkgd1 = Rectangle((0.01, 0.01), 0.5, 0.3, zorder=ord, color='white', lw=1.5) self.ax.add_artist(box_bkgd1) box_bkgd2 = Rectangle((0.41, 0.01), 0.1, 0.3, zorder=ord, lw=0) box_bkgd2.set_facecolor(self.core_color) self.ax.add_artist(box_bkgd2) box_bkgd3 = Rectangle((0.01, 0.01), 0.2, 0.3, zorder=ord, lw=0) box_bkgd3.set_facecolor(self.crust_color) self.ax.add_artist(box_bkgd3) box_bkgd4 = Rectangle((0.21, 0.01), 0.2, 0.3, zorder=ord, lw=0) box_bkgd4.set_facecolor(self.neutron_color) self.ax.add_artist(box_bkgd4) # Nuclei for j in range(0, 20): shift = rand() * 0.02 if j % 2 == 0: shift = shift + 0.15 / float(j + 2) for i in range(0, j + 2): y = 0.3 * float(i) / float(j + 2) + 0.01 + shift if y > 0.30: y = 0.30 nuc1 = Ellipse((0.02 + float(j) * 0.02, y), 0.01, 0.01, zorder=ord + 1, lw=0) nuc1.set_facecolor(self.core_color) self.ax.add_artist(nuc1) # Pasta for i in range(0, 60): y = 0.3 * float(i) / 60.0 if (y < 0.03): y = 0.03 pasta1 = Ellipse((0.40 - 0.1 * rand() * rand(), y), 0.01, 0.04, angle=rand() * 360, zorder=ord + 1, lw=0) pasta1.set_facecolor(self.core_color) self.ax.add_artist(pasta1) # Thinner pasta for i in range(0, 20): y = 0.3 * float(i) / 20.0 if (y < 0.04): y = 0.04 pasta2 = Ellipse((0.415 - 0.04 * rand() * rand(), y), 0.01, 0.06, angle=rand() * 60 - 30, zorder=ord + 1, lw=0) pasta2.set_facecolor(self.core_color) self.ax.add_artist(pasta2) # Labels self.ax.text(0.05, 0.12, 'Outer', fontsize=self.font_scale * 0.8, color='black', rotation='90', va='center', ha='center', zorder=ord + 2, bbox=dict(facecolor=self.crust_color, lw=0)) self.ax.text(0.09, 0.12, 'Crust', fontsize=self.font_scale * 0.8, color='black', rotation='90', va='center', ha='center', zorder=ord + 2, bbox=dict(facecolor=self.crust_color, lw=0)) self.ax.text(0.21, 0.12, 'neutron drip', fontsize=self.font_scale * 0.6, color='black', rotation='90', va='center', ha='center', zorder=ord + 2, bbox=dict(facecolor=self.crust_color, lw=0)) self.ax.text(0.25, 0.12, 'Inner', fontsize=self.font_scale * 0.8, color='black', rotation='90', va='center', ha='center', zorder=ord + 2, bbox=dict(facecolor=self.neutron_color, lw=0)) self.ax.text(0.29, 0.12, 'Crust', fontsize=self.font_scale * 0.8, color='black', rotation='90', va='center', ha='center', zorder=ord + 2, bbox=dict(facecolor=self.neutron_color, lw=0)) self.ax.text(0.38, 0.12, 'Pasta', fontsize=self.font_scale * 0.8, color='black', rotation='90', va='center', ha='center', zorder=ord + 2, bbox=dict(facecolor=self.core_color, lw=0)) self.ax.text(0.45, 0.12, 'Core', fontsize=self.font_scale * 0.8, color='black', rotation='90', va='center', ha='center', zorder=ord + 2) # Density labels self.ax.text(0.08, 0.24, 'g/cm$^{3}$:', fontsize=self.font_scale * 0.8, color='black', va='bottom', ha='center', zorder=ord + 2, bbox=dict(facecolor=self.crust_color, lw=0)) self.ax.text(0.18, 0.25, '$10^{11}$', fontsize=self.font_scale * 0.8, color='black', va='bottom', ha='center', zorder=ord + 2, bbox=dict(facecolor=self.crust_color, lw=0)) self.ax.text(0.39, 0.25, '$10^{14}$', fontsize=self.font_scale * 0.8, color='black', va='bottom', ha='center', zorder=ord + 2, bbox=dict(facecolor=self.core_color, lw=0)) # Crust thickness label self.ax.text(0.26, 0.335, '$R_{\mathrm{crust}}=0.4-2.0~\mathrm{km}$', fontsize=self.font_scale * 0.8, color=self.text_color, va='center', ha='center', zorder=13, bbox=dict(facecolor=self.bkgd_color, lw=0))
def bkgd(self): # Black background main_bkgd = Rectangle((0, 0), 1, 1) main_bkgd.set_facecolor(self.bkgd_color) self.ax.add_artist(main_bkgd)
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