def set_critical_labels(ax, k, m): """ Label the axis for the damping level with arrows to indicate the half critical, critical and twice critical damping levels. """ cr_label = Annotation(s=r"$b_{cr}$", xy=(2 * np.sqrt(k * m), 0), xytext=(2 * np.sqrt(k * m), -2), arrowprops=dict(arrowstyle='->')) ax.add_artist(cr_label) # Half-critical level. cr_label05 = Annotation(s=r"$b_{cr}$", xy=(np.sqrt(k * m), 0), xytext=(np.sqrt(k * m), -2), arrowprops=dict(arrowstyle='->')) ax.add_artist(cr_label05) # Twice critical level. cr_label2 = Annotation(s=r"$b_{cr}$", xy=(4 * np.sqrt(k * m), 0), xytext=(4 * np.sqrt(k * m), -2), arrowprops=dict(arrowstyle='->'), annotation_clip=False) ax.add_artist(cr_label2) ax.set_xlabel("Arrows show half critical, critical and twice critical " "damping levels respectfully.")
def transform_data(self): if self.cmd == 'find_source': self.points_list = self.idx.get_source_path( self.search_objects, self.exclude_sources, self.depth) elif self.cmd == 'find_target': self.points_list = self.idx.get_target_path( self.search_objects, self.depth) elif self.cmd == 'find': pl1 = self.idx.get_source_path(self.search_objects, self.exclude_sources, self.depth) pl2 = self.idx.get_target_path(self.search_objects, self.depth) self.points_list = pl1 + pl2 else: print('lol') exit(1) for ex in self.points_list.edges: arrow = FancyArrowPatch(ex[0], ex[1], arrowstyle='-|>', shrinkA=11, shrinkB=11, mutation_scale=10, color='black', linewidth=0.9, connectionstyle='arc3,rad=0.02', zorder=1) self.arrows.append(arrow) for point in self.points_list.points.values(): if point.name in self.search_objects: self.annotations.append( Annotation(point.name, point.xy, textcoords="offset points", xytext=(0, 11), ha='center', color='red', annotation_clip=True)) else: self.annotations.append( Annotation( point.name, # this is the text point.xy, # this is the point to label textcoords="offset points", # how to position the text xytext=(0, 11), # distance from text to points (x,y) ha= 'center', # horizontal alignment can be left, right or center annotation_clip=True))
def test_text_annotation_get_window_extent(): figure = Figure(dpi=100) renderer = RendererAgg(200, 200, 100) # Only text annotation annotation = Annotation('test', xy=(0, 0)) annotation.set_figure(figure) text = Text(text='test', x=0, y=0) text.set_figure(figure) bbox = annotation.get_window_extent(renderer=renderer) text_bbox = text.get_window_extent(renderer=renderer) eq_(bbox.width, text_bbox.width) eq_(bbox.height, text_bbox.height) _, _, d = renderer.get_text_width_height_descent( 'text', annotation._fontproperties, ismath=False) _, _, lp_d = renderer.get_text_width_height_descent( 'lp', annotation._fontproperties, ismath=False) below_line = max(d, lp_d) # These numbers are specific to the current implementation of Text points = bbox.get_points() eq_(points[0, 0], 0.0) eq_(points[1, 0], text_bbox.width) eq_(points[0, 1], -below_line) eq_(points[1, 1], text_bbox.height - below_line)
def test_arrow_annotation_get_window_extent(): figure = Figure(dpi=100) figure.set_figwidth(2.0) figure.set_figheight(2.0) renderer = RendererAgg(200, 200, 100) # Text annotation with arrow annotation = Annotation('', xy=(0.0, 50.0), xytext=(50.0, 50.0), xycoords='figure pixels', arrowprops={ 'facecolor': 'black', 'width': 8, 'headwidth': 10, 'shrink': 0.0 }) annotation.set_figure(figure) annotation.draw(renderer) bbox = annotation.get_window_extent() points = bbox.get_points() eq_(bbox.width, 50.0) assert_almost_equal(bbox.height, 10.0 / 0.72) eq_(points[0, 0], 0.0) eq_(points[0, 1], 50.0 - 5 / 0.72)
def _overlay_miri_ta_positions(): '''MIRI has eight target acq locations for each coronagraph which could result in persistence''' ta_loc_spot_radius = 0.2 # arcsec mask_name = re.match(r'MIRIM_CORON(\d+|LYOT)', aperture.AperName).groups()[0] ta_apers = [ 'MIRIM_TA{}_LL', 'MIRIM_TA{}_CLL', 'MIRIM_TA{}_LR', 'MIRIM_TA{}_CLR', 'MIRIM_TA{}_UL', 'MIRIM_TA{}_CUL', 'MIRIM_TA{}_UR', 'MIRIM_TA{}_CUR', ] ta_apt_name_lookup = { 'UR': 1, 'UL': 2, 'LL': 3, 'LR': 4, } for ta_aper in ta_apers: mask_ta_aper = ta_aper.format(mask_name) ta_loc = aperture.tel_to_idl(_MIRI_SIAF[mask_ta_aper].V2Ref, _MIRI_SIAF[mask_ta_aper].V3Ref) mask_artists.append(Circle(ta_loc, radius=ta_loc_spot_radius, color=GRAY_GGPLOT, alpha=0.25)) quadrant = mask_ta_aper[-2:] mask_artists.append(Annotation( 'TA {}'.format(ta_apt_name_lookup[quadrant]), ta_loc, xytext=(ta_loc[0], ta_loc[1] + 0.25), horizontalalignment='center', alpha=0.5, ))
def plot_mantissa_arc_test(df, gravity_center, grid=True, figsize=12): """Draws thee Mantissa Arc Test after computing X and Y circular coordinates for every mantissa and the center of gravity for the set Args: df (DataFrame): pandas DataFrame with the mantissas and the X and Y coordinates. gravity_center (tuple): coordinates for plottling the gravity center grid (bool): show grid. Defaults to True. figsize (int): figure dimensions. No need to be a tuple, since the figure is a square. """ fig = plt.figure(figsize=(figsize, figsize)) ax = plt.subplot() ax.set_facecolor(colors['b']) ax.scatter(df.mant_x, df.mant_y, label="ARC TEST", color=colors['m']) ax.scatter(gravity_center[0], gravity_center[1], color=colors['s']) text_annotation = Annotation( " Gravity Center: " f"x({round(gravity_center[0], 3)})," f" y({round(gravity_center[1], 3)})", xy=(gravity_center[0] - 0.65, gravity_center[1] - 0.1), xycoords='data') ax.add_artist(text_annotation) ax.grid(True, which='both') ax.axhline(y=0, color='k') ax.axvline(x=0, color='k') ax.legend(loc='lower left') ax.set_title("Mantissas Arc Test") plt.show(block=False)
def _get_text(txt, x, y, dx, dy, ha="center", va="center", **kwargs): if "color" in kwargs: textcolor = kwargs["color"] elif "markeredgecolor" in kwargs: textcolor = kwargs["markeredgecolor"] ann = Annotation(txt, (x, y), xytext=(dx, dy), xycoords='data', textcoords="offset points", ha=ha, va=va, **kwargs) ann.set_transform(IdentityTransform()) return ann
def plot_mantissa_arc_test(df, gravity_center, grid=True, figsize=12, save_plot=None, save_plot_kwargs=None): """Draws thee Mantissa Arc Test after computing X and Y circular coordinates for every mantissa and the center of gravity for the set Args: df (DataFrame): pandas DataFrame with the mantissas and the X and Y coordinates. gravity_center (tuple): coordinates for plottling the gravity center grid (bool): show grid. Defaults to True. figsize (int): figure dimensions. No need to be a tuple, since the figure is a square. save_plot: string with the path/name of the file in which the generated plot will be saved. Uses matplotlib.pyplot.savefig(). File format is infered by the file name extension. save_plot_kwargs: dict with any of the kwargs accepted by matplotlib.pyplot.savefig() https://matplotlib.org/api/_as_gen/matplotlib.pyplot.savefig.html """ fig = plt.figure(figsize=(figsize, figsize)) ax = plt.subplot() ax.set_facecolor(COLORS['b']) ax.scatter(df.mant_x, df.mant_y, label="ARC TEST", color=COLORS['m']) ax.scatter(gravity_center[0], gravity_center[1], color=COLORS['s']) text_annotation = Annotation( " Gravity Center: " f"x({round(gravity_center[0], 3)})," f" y({round(gravity_center[1], 3)})", xy=(gravity_center[0] - 0.65, gravity_center[1] - 0.1), xycoords='data') ax.add_artist(text_annotation) ax.grid(True, which='both') ax.axhline(y=0, color='k') ax.axvline(x=0, color='k') ax.legend(loc='lower left') ax.set_title("Mantissas Arc Test") if save_plot: if not save_plot_kwargs: save_plot_kwargs = {} plt.savefig(save_plot, **save_plot_kwargs) plt.show(block=False)
def _get_text(txt, x, y, dx, dy, ha="center", va="center", **kwargs): if "color" in kwargs: textcolor = kwargs["color"] del kwargs["color"] elif "markeredgecolor" in kwargs: textcolor = kwargs["markeredgecolor"] else: import matplotlib as mpl textcolor = mpl.rcParams['text.color'] ann = Annotation(txt, (x, y), xytext=(dx, dy), xycoords='data', textcoords="offset points", color=textcolor, ha=ha, va=va, **kwargs) ann.set_transform(IdentityTransform()) return ann
def __init__(self, ax, string, pos, dir, text_dict): from matplotlib.text import Annotation self.width = 0.1 self.height = 0.1 self.text = Annotation(string, pos, **text_dict) ax.add_artist(self.text) self.x, self.y = pos if dir == 'top': self.y += self.height / 2 elif dir == 'bottom': self.y -= self.height / 2 elif dir == 'right': self.x += self.width / 2 else: self.x -= self.width / 2
def test_empty_annotation_get_window_extent(): figure = Figure(dpi=100) figure.set_figwidth(2.0) figure.set_figheight(2.0) renderer = RendererAgg(200, 200, 100) # Text annotation with arrow annotation = Annotation( '', xy=(0.0, 50.0), xytext=(0.0, 50.0), xycoords='figure pixels') annotation.set_figure(figure) annotation.draw(renderer) bbox = annotation.get_window_extent() points = bbox.get_points() eq_(points[0, 0], 0.0) eq_(points[1, 0], 0.0) eq_(points[1, 1], 50.0) eq_(points[0, 1], 50.0)
def __init__(self, axes=None, id=0, length=5, width=2, label='car0', color='black'): self.id = id self.v = 0 self.set_pose(0, 0, 0) self.set_length_width(length, width) self.label = Annotation(label, [0, 0], size='small', annotation_clip=False) self.label.set_rotation_mode('anchor') self.bbox = Line2D([], [], 2, color=color) if axes: axes.add_line(self.bbox) axes.add_artist(self.label)
def update(frame): circles.set_offsets(list(zip(frame[0], frame[1]))) grad_vals = map(lambda x: -1 if x == float('inf') else int(floor(x)), world.gradients) i = 0 for label, x, y in zip(grad_vals, world.positions[0, :] + origin[0], world.positions[1, :] + origin[1]): anns[i].remove() ann = Annotation(label, xy=(x, y), xytext=(0, 0), textcoords='offset points', ha='center', va='center') ax.add_artist(ann) anns[i] = ann i += 1 circles.set_color(world.colors) circles.set_edgecolor('black') points.set_offsets(list(zip(frame[0] + frame[2], frame[1] + frame[3]))) return circles
def plot_triple_points(triple_points, line_length=8, axis=None): from matplotlib.text import Annotation import matplotlib.pyplot as plt if axis is None: axis = plt.gca() # Draw points for tp in triple_points: # Points for p in tp.branch_points + [tp.center]: axis.plot([p[0]], [p[1]], 'o', ms=5, color='k') line_ends = [] for p in tp.branch_points: center_to_p = p - tp.center center_to_p = center_to_p / np.linalg.norm( center_to_p) * line_length line_ends.append(tp.center + center_to_p) # Lines for target in line_ends: axis.plot([tp.center[0], target[0]], [tp.center[1], target[1]], '--', color='gray', lw=2) # Text for i in range(3): text_pos = (line_ends[i] + line_ends[(i + 1) % 3]) / 2 annotation = Annotation('%.1f°' % (tp.angles[i], ), (text_pos[0], text_pos[1]), axes=axis, fontsize=15, ha='center') axis.add_artist(annotation)
def animate(i): """ Draw motion of robots. """ for j in range(0, self.__num_agents): x = self.__states[0, j] y = self.__states[1, j] th = self.__states[2, j] pose_transformation_mat = np.array([ [np.cos(th), -1*np.sin(th), x], [np.sin(th), np.cos(th), y], [0, 0, 1]]) robot_body_transformed = np.dot(self.__robot_body, pose_transformation_mat.T) # New robot location. self.__robot_handle[j].set_xy(robot_body_transformed[:, 0:2]) # New Annotation location. self.__robot_number[j].remove() self.__robot_number[j] = Annotation( str(j + 1), xy=(x - self.__pos_bias, y - self.__pos_bias), xytext=(x - self.__pos_bias, y - self.__pos_bias)) self.ax.add_artist(self.__robot_number[j]) return self.__robot_handle
y_ = x * math.sin(yaw) + y * math.cos(yaw) return x_, y_ def local_to_global(self, x, y): x_, y_ = self.rotate(x, y, self.yaw) return x_ + self.x, y_ + self.y def global_to_local(self, x, y, offset, yaw): x_, y_ = x - self.x, y - self.y return self.rotate(x_, y_, -self.yaw) def to_figure_angle(self, radian): return -radian / math.pi * 180. t = Annotation('car0', xy=(2, 1), xytext=(3, 1.5), color='black') def main(): print("Test Car class") fig1 = plt.figure() ax1 = fig1.add_subplot(111, aspect='equal') car1 = Car(ax1, label='113') car1.set_pose(5, 5, math.pi / 4) car1.draw() car2 = Car(ax1, label='5422', color='r') car2.set_pose(0, 0, math.pi * 0.8) car2.set_pose(0, 0, 0) car2.draw()
from matplotlib import pyplot as plt from matplotlib.text import Annotation annot = Annotation('Dude', xy=(0.2, 0.2), xytext=(0.5, 0.8), arrowprops=dict(arrowstyle='->', color='r', lw=2)) fig, ax = plt.subplots() an1 = ax._add_text(annot) an1.set_bbox(dict(facecolor='red', boxstyle='circle', ls='dashed', lw=2)) an1.set_size(14) arrow = an1.arrow_patch arrow.set_linewidth(2) arrow.set_arrowstyle('-[') plt.show()
def annotate(axis, text, x, y): """ Worker function for interactive scatterplot""" text_annotation = Annotation(text, xy=(x, y), xycoords='data') axis.add_artist(text_annotation)
def annotate(axis, text, x, y): text_annotation = Annotation(text, xy=(x, y), xycoords='data') axis.add_artist(text_annotation)
world.positions[1, :] + fasePos[1, :])) fig = plt.figure(figsize=(8, 8)) ax = fig.add_axes([0, 0, 1, 1], frameon=False) ax.set_xlim(fieldSizeX1, fieldSizeX2), ax.set_xticks([]) ax.set_ylim(fieldSizeY1, fieldSizeY2), ax.set_yticks([]) plt.gca().set_aspect('equal', adjustable='box') grad_vals = map(lambda x: -1 if x == float('inf') else int(floor(x)), world.gradients) anns = [] for label, x, y in zip(grad_vals, world.positions[0, :] + origin[0], world.positions[1, :] + origin[1]): ann = Annotation(label, xy=(x, y), xytext=(0, 0), textcoords='offset points', ha='center', va='center') ax.add_artist(ann) anns.append(ann) circles = ax.add_collection( EllipseCollection(widths=2 * robotRadius, heights=2 * robotRadius, angles=0, units='xy', edgecolors='black', linewidth=0.5, facecolors=world.colors, offsets=startPos, transOffset=ax.transData))
def annotate(axis, text, x, y): # pragma: no cover """Create annotation at position (x,y) """ text_annotation = Annotation(text, xy=(x, y), xycoords='data') axis.add_artist(text_annotation)
xycoords='data', boxcoords="offset points", pad=0.0, arrowprops=dict(arrowstyle="->")) ab.set_zorder(-10) annotations2.append(ab) ax5.add_artist(ab) #ann=ax.annotate( #txt, #xy=(x2, y2), size=5, #bbox = dict(boxstyle = 'round,pad=0.1', fc = 'yellow', alpha = 0.2)) ann = Annotation(txt, xy=(x2, y2), size=5, bbox=dict(boxstyle='round,pad=0.1', fc='yellow', alpha=0.9)) ax5.add_artist(ann) textAnnotations2.append(ann) def update_position(e): for i in range(0, len(paintingImageLabels[::visualsSkip])): x2, y2, _ = proj3d.proj_transform( featureArraySplit[0][i * visualsSkip], featureArraySplit[1][i * visualsSkip], featureArraySplit[2][i * visualsSkip], ax5.get_proj()) annotations2[i].xy = x2, y2 annotations2[i].update_positions(fig4.canvas.renderer) #textAnnotations2[i].set_position((x2,y2))
def __init_robot_visualize(self): """ Initialize visualization for robots. The body of each robot consists of different parts, namely: grits_bot_left_wheel --> X, Y, Z points for left wheel grits_bot_right_wheel --> X, Y, Z points for right wheel grits_bot_tail_pin --> X, Y, Z points for tail pin grits_bot_base --> X, Y, Z points for robot base Each array consists for points on the graph that MATLAB/matplotlib use to form shapes. For example: grits_bot_base = [ 0, 0, 1; 1, 0, 1; 1, 1, 1; 0, 1, 1]; When all points are connected by lines, the grits bot base is generated. All robots are stored in the __robot_handle dictionary. Each robot is a matplotlib Polygon object and can be accessed with the appropriate index value. """ # Initialize variables. robot_diameter = 0.03 num_robots = self.__num_agents # Scale Factor (max value of single gaussian) # scale_factor = 0.5 fig_phi = plt.figure(1) self.figure_handle = fig_phi self.ax = self.figure_handle.add_subplot(111) # Plot Robotarium boundaries self.ax.spines['top'].set_color('c') self.ax.spines['bottom'].set_color('c') self.ax.spines['left'].set_color('c') self.ax.spines['right'].set_color('c') self.ax.set_xlim([self.__boundaries[0] - self.__offset, self.__boundaries[1] + self.__offset]) self.ax.xaxis.set_visible(False) self.ax.set_ylim([self.__boundaries[2] - self.__offset, self.__boundaries[3] + self.__offset]) self.ax.yaxis.set_visible(False) # Define custom patch variables """ Creating Grits Bot Base Matrix. """ val = np.sqrt(2) / 2 grits_bot_base = np.array([[(-1 * val), (-1 * val), 1], [val, (-1 * val), 1], [val, val, 1], [(-1 * val), val, 1], [(-1 * val), (-1 * val), 1], [val, (-1 * val), 1]]) grits_bot_base[:, 0:2] = grits_bot_base[:, 0:2] * robot_diameter """ Creating Grits Bot Left and Right Wheel Matrix """ grits_bot_wheel = np.array([[(-1 * val), (-1 * val), 1], [val, (-1 * val), 1], [val, val, 1], [(-1 * val), val, 1]]) grits_bot_wheel[:, 0:2] = np.dot(grits_bot_wheel[:, 0:2], np.diag([(robot_diameter / 3), (robot_diameter / 6)])) grits_bot_left_wheel = grits_bot_wheel + \ np.array([0, (7 / 6 * val * robot_diameter), 0]) grits_bot_right_wheel = grits_bot_wheel + \ np.array([0, (-7 / 6 * val * robot_diameter), 0]) """ Creating Grits Bot Tail Pin Matrix """ grits_bot_tail_pin_angle = np.arange((np.pi * 8 / 9), (np.pi * 10 / 9), (np.pi / 18))[:, np.newaxis] grits_bot_tail_pin = np.vstack( [np.array([[(-1 * val), np.sin(grits_bot_tail_pin_angle[0]), 1]]), np.hstack([np.cos(grits_bot_tail_pin_angle), np.sin(grits_bot_tail_pin_angle), np.ones(grits_bot_tail_pin_angle.shape)]), np.hstack([0.95 * np.cos(grits_bot_tail_pin_angle[::-1]), 0.95 * np.sin(grits_bot_tail_pin_angle[::-1]), np.ones(grits_bot_tail_pin_angle.shape)]), np.array([[(-1 * val), (0.95 * np.sin(grits_bot_tail_pin_angle[0])), 1]]) ]) grits_bot_tail_pin[:, 0:2] = grits_bot_tail_pin[:, 0:2] * \ robot_diameter """ Create Low Quality Version """ grits_bot_low_quality = np.array([[(-1 * val), (-1 * val), 1], [val, (-1 * val) + val/2, 1], [val, val - val/2, 1], [(-1 * val), val, 1], [(-1 * val), (-1 * val), 1], [val, (-1 * val) + val/2, 1]]) # Define common patch variables if not self.__low_quality: self.__robot_body = np.vstack([grits_bot_left_wheel, grits_bot_right_wheel, grits_bot_tail_pin, grits_bot_base]) else: self.__robot_body = grits_bot_low_quality self.__robot_body[:, 0:2] = self.__robot_body[:, 0:2] * \ robot_diameter # Create empty dictionary to place plt.Polygon objects. for i in range(0, num_robots): self.__robot_handle[i] = None # Set initial placement of agents on graph. for j in range(0, num_robots): x = self.__states[0, j] y = self.__states[1, j] th = self.__states[2, j] pose_transformation_mat = np.array([ [np.cos(th), -1*np.sin(th), x], [np.sin(th), np.cos(th), y], [0, 0, 1]]) robot_body_transformed = np.dot(self.__robot_body, pose_transformation_mat.T) # Visualize each robot. self.__robot_handle[j] = plt.Polygon( robot_body_transformed[:, 0:2]) self.__robot_handle[j].set_fill(True) self.__robot_handle[j].set_visible(True) self.__robot_handle[j].set_color(self.__robot_color) self.ax.add_patch(self.__robot_handle[j]) # Annotate each new robot. self.__robot_number[j] = Annotation(str(j+1), xy=(x-.01, y-.01), xytext=(x-.01, y-.01)) self.ax.add_artist(self.__robot_number[j]) # Show plot. if self.__ion: plt.ion() plt.show()