def add_logo_on_map(imagepath, ax, position, zoom, zorder): logo2plot = read_png(imagepath) imagebox = OffsetImage(logo2plot, zoom=zoom) # coordinates to position this image ab = AnnotationBbox(imagebox, position, xybox=(0.0, 0.0), xycoords="data", pad=0.0, boxcoords="offset points") ab.zorder = zorder ax.add_artist(ab)
def draw_mologram(self,position,turned): if turned: imagebox = OffsetImage(self.mologram_turned, zoom=.05) else: imagebox = OffsetImage(self.mologram, zoom=.05) ab = AnnotationBbox( imagebox, position, xybox= None, xycoords='data', boxcoords="offset points", frameon=False ) ab.zorder=1 self.ax.add_artist(ab)
def add_image(self, color): """Draw an image Parameters ---------- color : string. specify the color of the image to draw. The concatenation of the self.img_path and the color will give the complete path to the image. (ex: to draw a network in blue, self.img_path should='../ressources/network.png' and color='blue') """ if self.artist: self.artist.remove() self.color = color file_name, ext = os.path.splitext(self.img_path) new_path = file_name + color + ext image_path = get_sample_data(new_path) image = plt.imread(image_path) im = OffsetImage(image, zoom=self.zoom) ab = AnnotationBbox(im, (self.x, self.y), xycoords='data', frameon=False) ab.set_picker(5) self.artist = plt.gca().add_artist(ab) self.annotation_box = ab
def __plot_points_with_img(self, data, images): data_t = self.transform(data) # plot all points plt.plot(data_t[:, 0], data_t[:, 1], ".r") # draw images ax = plt.gcf().gca() for img, x, y in zip(images, data_t[:, 0], data_t[:, 1]): # add a first image imagebox = OffsetImage(img, zoom=.1) xy = [x, y] # coordinates to position this image ab = AnnotationBbox(imagebox, xy, # xybox=(arr_hand.shape[1] * 0.1 / 2, -arr_hand.shape[0] * 0.1 / 2), xybox=(0, 0), xycoords='data', boxcoords="offset points" ) ab.set_zorder(3) ax.add_artist(ab)
def background_image(self, file): """Set the file image as background image""" if self.bg_img: self.bg_img.remove() datafile = get_sample_data(file) img = plt.imread(datafile) im = OffsetImage(img) im.set_zoom(min(1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data']))) self.bg_img = AnnotationBbox(im, (0.5, 0.5), xycoords='data', frameon=False) self.bg_img.set_zorder(-1) plt.gca().add_artist(self.bg_img) self.do_refresh()
def graph4(self, lo, dday): if lo == 'All' and dday != 'All': de = self.ds5.loc[dday] fig = Figure(figsize=(7, 7)) plt = fig.add_subplot(111) s = list((de['Trips'] / de['Active_Vehicles'])) dc = (max(s) + min(s)) / 800 s = list(map(lambda x: round(x, 2), s)) t = list(de['Dispatch_Base']) b = OffsetImage(plti.imread('taxi2.png'), zoom=0.05) plt.scatter(de['Dispatch_Base'], (de['Trips'] / de['Active_Vehicles']), color='white') for x0, y0 in zip(de['Dispatch_Base'], (de['Trips'] / de['Active_Vehicles'])): ab = AnnotationBbox(b, (x0, y0), frameon=False) plt.add_artist(ab) plt.set_xlabel('Dispatch Bases') plt.set_ylabel('Trips per Vehicle') plt.set_title( f'Trips per Vehicle on week day {dday} of all locations') for i in range(len(s)): plt.annotate(s[i], (t[i], s[i] + dc)) canvas = FigureCanvasTkAgg(fig, master=self.root) canvas.get_tk_widget().place(x=780, y=100) canvas.draw() btn4 = Button(self.root, command=self.suggestion, text="Suggestions?", compound=LEFT, font=("Industry Inc Detail Fill", 20, "bold"), bg="white", fg="dimgray") btn4.place(x=930, y=620, height=50, width=200) else: messagebox.showerror( "Error", "Select the Correct Location and Week Day for this graph!")
def graph(self): fig = plt.figure(figsize=(23, 10.7)) ax = fig.add_subplot() if self.colors is None: plt.bar(self.x, self.y, edgecolor='black', linewidth=2,) else: plt.bar(self.x, self.y, edgecolor='black', linewidth=2, color=self.colors) plt.margins(0.01, 0.01) plt.grid(axis='y') if not self.x_ticks: plt.xticks([]) if self.labels is not None: for index in range(len(self.x)): image = OffsetImage(plt.imread(self.labels[index]), zoom=.13) ax.autoscale() if self.y[index] > 0: ly = -5 else: ly = 5 ab = AnnotationBbox(image, (self.x[index], ly), frameon=False) ax.add_artist(ab) plt.ylabel(self.y_label, fontsize=18) return plt
def make_image_annotation2(image, axes, x, y, size=1.0, bbox=None): # mage = Image.open(image) # Resize if necessary if size != 1.0: width, height = image.size width = width*size height = height*size image.thumbnail((width, height)) imagebox = OffsetImage(image) imagebox.image.axes = axes ab = AnnotationBbox(imagebox, (x, y), xycoords='axes fraction', boxcoords="offset points", pad=0, frameon=False, box_alignment=(0.5, 0) ) axes.add_artist(ab) return imagebox
def make_image_annotation(icon, axes, x, y, size=1.0): icon = Image.open(icon) icon = icon.convert("RGBA") # Resize if necessary if size != 1.0: width, height = icon.size width = width*size height = height*size icon.thumbnail((width, height)) imagebox = OffsetImage(icon) imagebox.image.axes = axes ab = AnnotationBbox(imagebox, (x, y), xycoords='axes fraction', boxcoords="offset points", pad=0, frameon=False ) axes.add_artist(ab) return imagebox
def build_first_plot(df): def getImage(path): return OffsetImage(plt.imread(path)) logos = os.listdir(os.getcwd() + '\\logos') logolist = [] for l in logos: logolist.append(os.getcwd() + '\\logos\\' + l) x = df['success'] y = df['epa'] fig, ax = plt.subplots(figsize=(10, 10)) ax.scatter(x, y, s=0.1) ax.set_title('Success Rate vs. EPA/Play', {"fontsize": 24}) ax.set_xlabel('Success Rate', {"fontsize": 18}) ax.set_ylabel('EPA/Play', {"fontsize": 18}) for x0, y0, path in zip(x, y, logolist): ab = AnnotationBbox(getImage(path), (x0, y0), frameon=False, fontsize=4) ax.add_artist(ab)
def visualize_scatter_with_images(X_2d_data, images, figsize=(12, 12), image_zoom=1.75, title='Class Scatter'): ''' X_2d_data is an embedding such as TSNE expects images in the following two shapes: 3-D np.array of the form [num_imgs x height x width] 4-D np.array of the form [num_imgs x height x width x 3] for three channel images ''' fig, ax = plt.subplots(figsize=figsize) artists = [] for xy, i in zip(X_2d_data, images): x0, y0 = xy img = OffsetImage(i, zoom=image_zoom) ab = AnnotationBbox(img, (x0, y0), xycoords='data', frameon=False) artists.append(ax.add_artist(ab)) ax.update_datalim(X_2d_data) ax.autoscale() plt.title(title, fontsize=20) plt.show()
def display(car, map, i): global ax plt.figure(1) plt.clf() #Pour ne pas superposer les images qui se succèdent fig = display_init(map) car.orientate() arr_lena1 = mpimg.imread('voiture_' + car.orientation + '.png') #charge l'image de la voiture imagebox1 = OffsetImage(arr_lena1, zoom=2) #config de la taille de la voiture ab1 = AnnotationBbox( imagebox1, car.pos, frameon=False, box_alignment=(0.5, 0.5)) #associer une image à une position ax.add_artist( ab1) # ajouter l'image à la fenêtre en utilisant la classe artist map.trace_map() ''' fig.savefig('frame_'+str(i)+'.png') #sert à enregister les frames de la simulation ''' plt.pause(0.0000000000000000000001)
def _visualize_scatter_with_images(x_2d_data, images, figsize=(30, 30), image_zoom=1): """ shows a scatter plot of 2d feature vector in a way that each point is marked with its corresponding image :param x_2d_data: 2d data to be shown in scatter plot :param images: images associated with each data point :param figsize: size of the plot :param image_zoom: zooming of the original image to be used as marker :return: scatter plot of the data with image markers """ fig, ax = plt.subplots(figsize=figsize) artists = [] for xy, i in zip(x_2d_data, images): x0, y0 = xy img = OffsetImage(i, zoom=image_zoom) ab = AnnotationBbox(img, (x0, y0), xycoords='data', frameon=False) artists.append(ax.add_artist(ab)) ax.update_datalim(x_2d_data) ax.autoscale() plt.show() """
def coil_image_scatter(): """在coil数据的降维结果中展示图片""" path = "E:\\Project\\DataLab\\imageScatter\\" small_image(eta=0.15, in_path=path + "images\\", out_path=path + "smallImages\\") Y = np.loadtxt(path + "mds3classk20yita01.csv", dtype=np.float, delimiter=",") (n, m) = Y.shape fig, ax = plt.subplots() ax.scatter(Y[:, 0], Y[:, 1]) for i in range(0, n): obj = i // 72 + 1 img_index = i % 72 ab = AnnotationBbox(get_image(path + "smallImages\\obj" + str(obj) + "__" + str(img_index) + ".png"), (Y[i, 0], Y[i, 1]), frameon=False) ax.add_artist(ab) ax = plt.gca() ax.set_aspect(1) plt.show()
def plot_image(self, x_lim, y_lim, ax, path='../Computational_Data/Images/', i=0, xycoords='data'): image = self.dict['Image'][i] if image != 'No': vert_off = self.dict['Vertical_Offset'][i] horiz_off = self.dict['Horizontal_Offset'][i] img = mpimg.imread(path + image) imagebox = OffsetImage(img, zoom=self.dict['Zoom'][i]) ab = AnnotationBbox(imagebox, (x_lim - horiz_off, y_lim + vert_off), frameon=False, xycoords=xycoords) ax.add_artist(ab)
def _save_line_graph(scores: list, urls: list): images, graph_size = _get_line_graph_images(urls) size = graph_size[0] / 100 vector_figure = plt.figure( figsize=[graph_size[0] / 100, graph_size[1] / 100]) axes = plt.axes() axes.set_title("Fruit Vectors", size=size * 3) axes.set_ylabel("Score", size=size * 3) axes.set_xlabel("Day", size=size * 3) plt.setp(axes.get_xticklabels(), size=size * 2) plt.setp(axes.get_yticklabels(), size=size * 2) axes.plot(scores, color="black", marker="o", markerfacecolor="red", linewidth=5) count = 0 for score in scores: ab = AnnotationBbox(images[count], (count, score), frameon=False) axes.add_artist(ab) count += 1 vector_figure.add_axes(axes) vector_figure.savefig("./line.png", bbox_inches="tight")
def main(): fig, ax = plt.subplots(1, 1) artists = [] x = [0, 1, 2, 3, 4] y = [0, 1, 2, 3, 4] A = np.random.random(size=(5, 5)) ax.matshow(A) xl, yl, xh, yh = np.array(ax.get_position()).ravel() print(xl, yl, xh, yh) w = xh - xl h = yh - yl xp = xl + w * 0.5 #if replace '0' label, can also be calculated systematically using xlim() print(xp) size = 0.01 #for x0, y0 in zip(x, y): ab = AnnotationBbox(getImage('../lib/todd2.jpg'), (xp - size * 0.5, yh), frameon=False, box_alignment=(0., 0.)) artists.append(ax.add_artist(ab)) plt.show()
def _plot_dial(fig_handle, ax_handle, val, max_val, maxed_pos, maxed_asset, icon_asset, dial_colour): ccw = False if 0 < val <= max_val: groups = [val / max_val, 1 - val / max_val] elif val == 0: groups = [0.01, 0.99] elif val >= max_val: groups = [max_val, 0] _add_maxed(fig_handle, maxed_pos, maxed_asset) else: # only valid for temperature where a negative value is possible groups = [abs(val) / max_val, 1 - abs(val) / max_val] ccw = True ax_handle.pie(groups, colors=[dial_colour, DisplayConfig.SEGMENTS], startangle=90, counterclock=ccw) my_circle = plt.Circle((0, 0), 0.7, color=DisplayConfig.BACKGROUND) ax_handle.add_artist(my_circle) im_icon = mpimg.imread(icon_asset) icon = OffsetImage(im_icon, zoom=0.18) ab_icon = AnnotationBbox(icon, (0, 0), frameon=False) ax_handle.add_artist(ab_icon)
def image_placer(self, _, industry): _.set_title(industries[industry], fontsize = 8) count = 1 new = file.loc[file['Your industry'] == industries[industry]] size = 30, 30 for i in new['Logo']: png = i.split('/', 1)[-1].replace('/', '') r = requests.get(i, stream = True) with open('logos/'+png, 'wb') as out_file: shutil.copyfileobj(r.raw, out_file) del r img = Image.open('logos/'+png) img.thumbnail(size, Image.ANTIALIAS) '''img.save('logos/'+png) arr_AS = mpimg.imread('logos/'+png)''' imagebox = OffsetImage(img) if count == 1: x, y = 0.2, 0.2 elif count > 1 and count < 4: x += 0.3 elif count == 4: x = 0.2 y = 0.5 elif count > 4 and count < 7: x += 0.3 elif count == 7: x = 0.2 y = 0.8 elif count > 8 and count < 10: x += 0.3 elif count == 10: x, y = 0.2, 0.2 count = 1 break AS = AnnotationBbox(imagebox, (x, y), frameon=False, pad=0) count += 1 _.add_artist(AS)
def draw_token(cls, token, r, c, ax, height, width, token_scale=1.0): if token == EMPTY: edge_color = '#888888' face_color = 'white' drawing = RegularPolygon((c + 0.5, (height - 1 - r) + 0.5), numVertices=4, radius=0.5 * np.sqrt(2), orientation=np.pi / 4, ec=edge_color, fc=face_color) ax.add_patch(drawing) return drawing else: edge_color = '#888888' face_color = '#DDDDDD' drawing = RegularPolygon((c + 0.5, (height - 1 - r) + 0.5), numVertices=4, radius=0.5 * np.sqrt(2), orientation=np.pi / 4, ec=edge_color, fc=face_color) ax.add_patch(drawing) im = TOKEN_IMAGES[token] oi = OffsetImage(im, zoom=cls.fig_scale * (token_scale / max(height, width)**0.5)) box = AnnotationBbox(oi, (c + 0.5, (height - 1 - r) + 0.5), frameon=False) ax.add_artist(box) return box
def receive_map(self) -> None: """ Updates the UI when a new map is available for display """ children = self.plotWidget.canvas.ax.get_children() for c in children: if isinstance(c, AnnotationBbox): c.remove() zoom, radius, map_image, mark = self.map_data.get_map_value() # plotMap UI modification self.plotWidget.canvas.ax.set_axis_off() self.plotWidget.canvas.ax.set_ylim(map_image.shape[0], 0) self.plotWidget.canvas.ax.set_xlim(0, map_image.shape[1]) # Removes pesky white boarder self.plotWidget.canvas.fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) if self.im: # Required because plotting images over old ones creates memory leak # NOTE: im.set_data() can also be used self.im.remove() self.im = self.plotWidget.canvas.ax.imshow(map_image) # updateMark UI modification for i in range(len(mark)): annotation_box = AnnotationBbox(OffsetImage(MAP_MARKER), mark[i], frameon=False) self.plotWidget.canvas.ax.add_artist(annotation_box) # For debugging marker position #self.plotWidget.canvas.ax.plot(mark[1][0], mark[1][1], marker='o', markersize=3, color="red") self.plotWidget.canvas.draw() MAP_UPDATED_EVENT.increment()
def plot_digits(X, y, min_distance=0.05, images=None, figsize=(13, 10)): # Let's scale the input features so that they range from 0 to 1 X_normalized = MinMaxScaler().fit_transform(X) # Now we create the list of coordinates of the digits plotted so far. # We pretend that one is already plotted far away at the start, to # avoid `if` statements in the loop below neighbors = np.array([[10., 10.]]) # The rest should be self-explanatory plt.figure(figsize=figsize) cmap = matplotlib.cm.get_cmap("jet") digits = np.unique(y) for digit in digits: plt.scatter(X_normalized[y == digit, 0], X_normalized[y == digit, 1], c=cmap(digit / 9), s=2) plt.axis("off") ax = plt.gcf().gca() # get current axes in current figure for index, image_coord in enumerate(X_normalized): closest_distance = np.linalg.norm(np.array(neighbors) - image_coord, axis=1).min() if closest_distance > min_distance: neighbors = np.r_[neighbors, [image_coord]] if images is None: plt.text(image_coord[0], image_coord[1], str(int(y[index])), color=cmap(y[index] / 9), fontdict={ "weight": "bold", "size": 16 }) else: image = images[index].reshape(28, 28) imagebox = AnnotationBbox(OffsetImage(image, cmap="binary"), image_coord) ax.add_artist(imagebox)
def tipsquares(plot, p, colors='r', size=15, pad=2, edgepad=10): """ RR: Bug with this function. If you attempt to call it with a list as an argument for p, it will not only not work (expected) but it will also make it so that you can't interact with the tree figure (gives errors when you try to add symbols, select nodes, etc.) -CZ Add square after tip label, anchored to the side of the plot Args: plot (Tree): A Tree plot instance. p (Node): A Node object (Should be a leaf node). colors (str): color of drawn square. Optional, defaults to 'r' (red) size (float): Size of square. Optional, defaults to 15 pad: RR: I am unsure what this does. Does not seem to have visible effect when I change it. -CZ edgepad (float): Padding from square to edge of plot. Optional, defaults to 10. """ x, y = _xy(plot, p) # p is a single node or point in data coordinates n = len(colors) da = DrawingArea(size * n + pad * (n - 1), size, 0, 0) sx = 0 for c in colors: sq = Rectangle((sx, 0), size, size, color=c) da.add_artist(sq) sx += size + pad box = AnnotationBbox(da, (x, y), xybox=(-edgepad, y), frameon=False, pad=0.0, xycoords='data', box_alignment=(1, 0.5), boxcoords=('axes points', 'data')) plot.add_artist(box) plot.figure.canvas.draw_idle()
def _add_image(ax,fname = None,loc = (.5,.5),**kwargs): fname = fname.replace(' ','_') fname = fname.replace("'",'_') if not os.path.isfile(fname): print '{} not found!'.format(fname) return print 'Adding image: {}'.format(fname) arr_img = plt.imread(fname, format='png') imagebox = OffsetImage(arr_img, zoom=0.175,resample=True, dpi_cor=False) imagebox.image.axes = ax ab = AnnotationBbox(imagebox, loc, xycoords='data', boxcoords="offset points", frameon=False, arrowprops=dict( arrowstyle="->", connectionstyle="angle,angleA=0,angleB=90,rad=3") ) ax.add_artist(ab)
def plot_dog_atlas(embed, meta_df, title, ax): # fitting kmeans to get evenly spaced points on MAP km = KMeans(n_clusters=100) km.fit(embed) # getting these centroids centroids = km.cluster_centers_ medoids = (pd.DataFrame(embed).apply( lambda x: km.score(x.values.reshape(1, -1)), axis=1).groupby(km.predict(embed)).idxmax()) # images to plot img_to_plot = meta_df.index.values[medoids] # plotting a light scatter plot #fig, ax = plt.subplots(figsize=(12,6), dpi=120) ax.scatter(embed[:, 0], embed[:, 1], s=2, alpha=0.1, color='black') # loop adding pictures to plot for i, img in enumerate(img_to_plot): img = plt.imread(img) imagebox = OffsetImage(img, zoom=0.1) imagebox.image.axes = ax ab = AnnotationBbox(imagebox, embed[medoids[i]], pad=0) ax.add_artist(ab) # title and other info ax.set_title(title) ax.set_xlabel('first UMAP dimension') ax.set_ylabel('second UMAP dimension') plt.grid(b=None) ax.set_xticks([]) ax.set_yticks([])
def scatter(x, colors): # We choose a color palette with seaborn. palette = np.array(sns.color_palette("hls", 10)) # We create a scatter plot. f = plt.figure() ax = plt.subplot() sc = ax.scatter(x[:, 0], x[:, 1], lw=0, s=40, c=palette[1]) plt.xlim(-400, 400) plt.ylim(-400, 400) ax.axis('off') ax.axis('tight') img_boxs = [] for ind, point in zip(range(len(x)), x): oImg = OffsetImage(plt.imread(image_paths[ind]), zoom=.2) ab = AnnotationBbox(oImg, xy=(point[0], point[1]), xycoords='data', boxcoords="offset points") img_boxs.append(ax.add_artist(oImg)) print('ImgBox[%d]' % ind) return f, ax, sc, img_boxs
def plot_digits(X, y, min_distance=0.05, images=None, figsize=(13, 10)): # Scale the input features for range 0 to 1 X_normalized = MinMaxScaler().fit_transform(X) # Create the list of coordinates of the digits plotted # Create one initially neighbors = np.array([[10., 10.]]) plt.figure(figsize=figsize) cmap = matplotlib.cm.get_cmap("jet") digits = np.unique(y) for digit in digits: plt.scatter( X_normalized[y == digit, 0], X_normalized[y == digit, 1], c=cmap(digit / 9)) plt.axis("off") ax = plt.gcf().gca() for index, image_coord in enumerate(X_normalized): closest_distance = np.linalg.norm( np.array(neighbors) - image_coord, axis=1).min() if closest_distance > min_distance: neighbors = np.r_[neighbors, [image_coord]] if images is None: plt.text( image_coord[0], image_coord[1], str(int(y[index])), color=cmap(y[index] / 9), fontdict={ "weight": "bold", "size": 16 }) else: image = images[index].reshape(28, 28) imagebox = AnnotationBbox( OffsetImage(image, cmap="binary"), image_coord) ax.add_artist(imagebox)
def add_image(name: str, x: float or int, y: float or int, offset: float, zoom: float = 0.20) -> AnnotationBbox: """ Adds the given image to the bar graph, with the given specifications. Args: name - Should be a string representing name of the file to open (without file extension) x - x-coordinate y - y-coordinate offset - By how much to the left or right should the image be placed. Is applied only to x coordinate. zoom - Controls how big the image is. """ # Open image as numpy array- try: pic_file = get_sample_data(f"{cwd}/profile_pics/{name}.png") except FileNotFoundError: # When user has no profile pic, or changed their dp privacy settings pic_file = get_sample_data(f"{cwd}/profile_pics/nobody.png") with pic_file as file: arr_img = plt.imread(file, format='jpg') image_box = OffsetImage(arr_img, zoom=zoom) # zoom changes the size of the image # Adds image to the provided coordinates- return AnnotationBbox(image_box, (x + offset, y), frameon=False, annotation_clip=False)
def plot_pixel_level_results_as_image_graph(): Y, files = torch.load('../tsne_output_pix.pth') fig, ax = pyplot.subplots() fig.set_size_inches(200,200,forward=True) ax.update_datalim(np.column_stack([Y[:, 0], Y[:, 1]])) ax.autoscale() expansion = 8 # Should be latent_compression(=8) * image_compression_at_inference(=1) margins = 4 # Keep in mind this will be multiplied by <expansion> for b in tqdm(range(Y.shape[0])): if b % 4 == 0: id = b // 4 imgfile = files[id] baseim = pyplot.imread(imgfile) ct, cl = random_coords[b%4] im = baseim[expansion*(ct-margins):expansion*(ct+margins), expansion*(cl-margins):expansion*(cl+margins),:] im = OffsetImage(im, zoom=1) ab = AnnotationBbox(im, (Y[b, 0], Y[b, 1]), xycoords='data', frameon=False) ax.add_artist(ab) ax.scatter(Y[:, 0], Y[:, 1]) pyplot.savefig('tsne_pix.pdf')
def plot_progress(self, error_series, plt_imgs, plt_imgs_t): """ This method generates an informative plot, displaying the loss over time along logged images. :param error_series: loss values over time (/ steps) :param plt_imgs: logged images :param plt_imgs_t: time (/ step) at which respective images have been logged :return: """ fig, ax = plt.subplots(figsize=(160, 40)) ax.plot(np.arange(1, 1 + len(error_series)), error_series, alpha=0.9) for i, p_I in enumerate(plt_imgs): imagebox = OffsetImage(p_I, zoom=1.) x = plt_imgs_t[i] ab = AnnotationBbox(imagebox, (x, error_series[x - 1]), xybox=(0., 256.), xycoords='data', boxcoords="offset points", arrowprops={'arrowstyle': '->'}) ax.add_artist(ab) plt.savefig(join(f'logs/{self.model_name}/progress.png'), bbox_inches='tight', dpi=50) plt.close(fig)
def average_age_visualize(save): data = pd.read_csv('Data/average_age.csv') df = pd.DataFrame(data) fig, ax = plt.subplots(figsize=(20, 15)) ax.title.set_text('Average age of each NFL team') for index in df.index: row = str(df.iloc[index]).split(' ') row = remove_spaces(row) team = row[1].replace('age', '').replace(' ', '') age = row[2].replace('Name:', '') team = team.replace('\r\n', '\n').replace('\n', '') image = team + '.png' ax.scatter(team, float(age), c='w') ab = AnnotationBbox(OffsetImage(plt.imread(image, 0)), (team, float(age)), frameon=False) ax.add_artist(ab) ax.axhline(y=avg_list(df['age']), color='black') if save: plt.savefig('avgage.png') else: plt.show()
def image_scatter(): path = "E:\\Project\\DataLab\\duck\\" path1 = "E:\\Project\\DataLab\\duck\\images\\" path2 = "E:\\Project\\DataLab\\duck\\smallimages\\" small_image(eta=0.3, in_path=path1, out_path=path2) image_path = path + "smallimages\\obj1__" X = np.loadtxt(path + "data.csv", dtype=np.float, delimiter=",") X = preprocessing.minmax_scale(X) (n, m) = X.shape print((n, m)) pca = PCA(n_components=2) Y = pca.fit_transform(X) fig, ax = plt.subplots() ax.scatter(Y[:, 0], Y[:, 1]) for i in range(0, n): ab = AnnotationBbox(get_image(image_path + str(i) + ".png"), (Y[i, 0], Y[i, 1]), frameon=False) ax.add_artist(ab) ax = plt.gca() ax.set_aspect(1) plt.show()
def imscatter(x, y, images, ax=None, zoom=1, lw=0, color='black'): if ax is None: ax = plt.gca() x, y = np.atleast_1d(x, y) artists = [] for x0, y0, image in zip(x, y, images): image = plt.imread(image) im = OffsetImage(image, zoom=zoom) ab = AnnotationBbox(im, (x0, y0), xycoords='data', frameon=True, bboxprops=dict(edgecolor=color, boxstyle="square,pad=0", lw=lw)) artists.append(ax.add_artist(ab)) ax.update_datalim(np.column_stack([x, y])) ax.autoscale() return artists
def generate_map(self, lat, lon): lat = float(lat) lon = float(lon) icon = join(dirname(__file__), self.settings["iss_icon"]) output = join(tempfile.gettempdir(), "iss.jpg") lat_0 = None lon_0 = None if self.settings["center_iss"]: lat_0 = lat lon_0 = lon elif self.settings["center_location"]: lat_0 = self.location["coordinate"]["latitude"] lon_0 = self.location["coordinate"]["longitude"] if self.settings["map_style"] == "cyl": lat_0 = None lon_0 = None m = Basemap(projection=self.settings["map_style"], resolution=None, lat_0=lat_0, lon_0=lon_0) m.bluemarble() x, y = m(lon, lat) iss = plt.imread(icon) im = OffsetImage(iss, zoom=self.settings["iss_size"]) ab = AnnotationBbox(im, (x, y), xycoords='data', frameon=False) # Get the axes object from the basemap and add the AnnotationBbox artist m._check_ax().add_artist(ab) plt.savefig(output, dpi=self.settings["dpi"], bbox_inches='tight', facecolor="black") plt.close() return output
def imscatter( x: np.ndarray, y: np.ndarray, ax: Axes, imageData: torch.Tensor, unnormalize_fn: Optional[Callable] = None, zoom: int = 1, ) -> NoReturn: """Scatter plot with images instead of points on ax.""" images = [] for i in range(len(x)): x0, y0 = x[i], y[i] # Convert to image img = imageData[i] if unnormalize_fn is not None: img = unnormalize_fn(img) img *= 255.0 img = img.permute([1, 2, 0]).numpy().astype(np.uint8) image = OffsetImage(img, zoom=zoom) ab = AnnotationBbox(image, (x0, y0), xycoords="data", frameon=False) images.append(ax.add_artist(ab)) ax.update_datalim(np.column_stack([x, y])) ax.autoscale()
import matplotlib.pyplot as plt ax = plt.subplot(111) ax.plot([1,2,3], label="test") l = ax.legend() d1 = l.draggable() xy = 1, 2 txt = ax.annotate("Test", xy, xytext=(-30, 30), textcoords="offset points", bbox=dict(boxstyle="round",fc=(0.2, 1, 1)), arrowprops=dict(arrowstyle="->")) d2 = txt.draggable() from matplotlib._png import read_png from matplotlib.cbook import get_sample_data from matplotlib.offsetbox import OffsetImage, AnnotationBbox fn = get_sample_data("lena.png", asfileobj=False) arr_lena = read_png(fn) imagebox = OffsetImage(arr_lena, zoom=0.2) ab = AnnotationBbox(imagebox, xy, xybox=(120., -80.), xycoords='data', boxcoords="offset points", pad=0.5, arrowprops=dict(arrowstyle="->", connectionstyle="angle,angleA=0,angleB=90,rad=3") ) ax.add_artist(ab) d3 = ab.draggable(use_blit=True) plt.show()
ax.yaxis.pan(+1) elif event.key == 'down': ax.yaxis.pan(-1) draw() fig = figure() fig.canvas.mpl_connect('key_press_event', onpress) ax = fig.gca() ann = AnnotationBbox(OffsetImage(np.arange(256).reshape(16,16)/256.0, zoom=2, norm = None, origin=None), (0.5, 0.5), xybox=(30, 30), xycoords='data', boxcoords="offset points", frameon=True, pad=0.4, # BboxPatch bboxprops=dict(boxstyle="round", fc="y"), fontsize=None, arrowprops=dict(arrowstyle="->")) ax.add_artist(ann) ann.draggable() show() #draggable = DraggableAnnotation(a, use_blit=True)
class Gtk_NetworkCanvas: """Gtk_NetworkCanvas class. This class contains the canvas to draw the topology. It implements event listener and zoom. Parameters ---------- canvas : the gtk canvas to draw adjustement : used for zoom scroll bar zoom_scale : a scroll bar to zoom redraw : a button to redraw the graph popup : a popup for interaction on right click bRefresh : bool. if True enable refresh with do_refresh function corners : the limit of the canvas drawing area press : bool. True if mouse click on canvas (used for zoom) x_old, y_old : position for zoom """ def __init__(self): fig = plt.figure(num=None, facecolor='w', edgecolor='k') plt.axis('off') plt.subplots_adjust(left=0., right=1., bottom=0., top=1., wspace=0.2, hspace=0.2) self.canvas = FigureCanvas(fig) self.canvas.add_events( gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK | gtk.gdk.BUTTON_RELEASE_MASK) self.canvas.connect("motion_notify_event", self.on_motion) self.canvas.connect("button-press-event", self.on_click) self.canvas.connect("button-release-event", self.on_release) self.canvas.connect("scroll-event", self.on_scroll) self.canvas.connect("leave-notify-event", self.on_lose_focus) self.adjustement = gtk.Adjustment(0.0, 0.0, 100.0, 1.0, 1.0, 1.0) self.adjustement_signal = self.adjustement.connect("value-changed", self.on_zoom_changed) self.zoom_scale = gtk.HScale(self.adjustement) self.zoom_scale.set_draw_value(False) self.zoom_value = 0.0 self.redraw = gtk.Button("Redraw") self.redraw.connect("clicked", self.on_redraw) self.hbox = gtk.HBox() self.hbox.pack_start(self.zoom_scale, True, True, 0) self.hbox.pack_end(self.redraw, False, False, 0) self.vbox = gtk.VBox() self.vbox.pack_start(self.canvas, True, True, 0) self.vbox.pack_end(self.hbox, False, False, 0) self.popup = Gtk_NewtworkPopupMenu() self.bRefresh = True self.corners = None self.press = False self.x_old = 0 self.y_old = 0 self.bg_img = None def on_click(self, widget, event): """Event listener : click If double left click : - on edge, show edges rules - on firewall, show firewall conf - on interface, add note If left click : - on edge, show message - on firewall, show message interaction firewall - on interface, show message interaction interface - else move x/y limit drawing area If right click : - on edge, show edge menu - on firewall, show firewall menu - on interface, show interface menu - else show canvas menu """ if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS: dbl_click = False dbl_click |= self.on_dblclick_edge() dbl_click |= self.on_dblclick_node() if not dbl_click: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message(Gtk_Message.TOPOLOGY_MESSAGE) if event.button == 3 and event.type == gtk.gdk.BUTTON_PRESS: right_click = False right_click |= self.on_right_click_edge(event) right_click |= self.on_right_click_node(event) if not right_click: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message(Gtk_Message.ON_BACKGROUND_CLICK) self.popup.popup_clear(event) if event.button == 1 and event.type == gtk.gdk.BUTTON_PRESS: left_click = False left_click |= self.on_left_click_edge() left_click |= self.on_left_click_node() if not left_click: self.press = True self.x_old = event.x self.y_old = event.y Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message(Gtk_Message.TOPOLOGY_MESSAGE) return True def on_dblclick_edge(self): """Show interface rules""" def get_firewall(x, y): if isinstance(x, Firewall): return x elif isinstance(y, Firewall): return y return None def get_ip(x, y): if isinstance(x, Ip): return x elif isinstance(y, Ip): return y return None g = NetworkGraph.NetworkGraph() for elem in g.graph.edges(data=True): edge = elem[2]['object'] if edge.gtk_press: fw = get_firewall(elem[0], elem[1]) ip = get_ip(elem[0], elem[1]) result = [] [result.append(acl) for acl in g.get_acl_list(src=ip, dst=None, firewall=fw)] [result.append(acl) for acl in g.get_acl_list(src=None, dst=ip, firewall=fw)] if not result: Gtk_DialogBox("No rules found for this interface !") [Gtk_Main.Gtk_Main().notebook.add_interface_tab(acl) for acl in result] return True return False def on_dblclick_node(self): """Event listener, on double click node, if firewall show conf file else add note""" g = NetworkGraph.NetworkGraph() for k, v in g.graph.node.items(): if v['object'].gtk_press and isinstance(v['object'].object, Firewall): Gtk_Main.Gtk_Main().notebook.add_conf_tab(v['object'].object.name, v['object'].object.hostname) return True if v['object'].gtk_press and isinstance(v['object'].object, Ip): self.popup.node = v['object'] self.popup.on_add_note(None) return True return False def on_right_click_edge(self, event): """Event listener, on right click edge, popup menu showing acl list of related to this interface""" g = NetworkGraph.NetworkGraph() for elem in g.graph.edges(data=True): edge = elem[2]['object'] if edge.gtk_press: self.popup.popup(elem, event, edge) edge.gtk_press = False return True return False def on_right_click_node(self, event): """Event listener, on right click node, show popup menu for node""" g = NetworkGraph.NetworkGraph() for k, v in g.graph.node.items(): if v['object'].gtk_press: self.popup.popup(None, event, v['object']) v['object'].gtk_press = False return True return False def on_left_click_node(self): """Show node details""" g = NetworkGraph.NetworkGraph() for k, v in g.graph.node.items(): if v['object'].gtk_press: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message(Gtk_Message.ON_CLICK_NODE) Gtk_Main.Gtk_Main().lateral_pane.details.clear() tmp_intf = [e[2]['object'].object for e in g.graph.edges(k, data=True)] for e in sorted(tmp_intf, key=lambda tmp_intf: tmp_intf.nameif): message = "%s:\n- %s\n- %s" % (e.nameif, e.name, e.network.to_string()) for key, value in e.attributes.items(): message += "\n- %s : %s" % (key, value) Gtk_Main.Gtk_Main().lateral_pane.details.add_row(message) Gtk_Main.Gtk_Main().lateral_pane.focus_details() return True return False def on_left_click_edge(self): """If left click edge, show help message""" g = NetworkGraph.NetworkGraph() for edge in g.graph.edges(): if g.graph[edge[0]][edge[1]]['object'].gtk_press: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message(Gtk_HelpMessage.Gtk_Message.ON_CLICK_EDGE) return True return False def on_motion(self, widget, event): """If not click node, then move axis""" if self.press and self.corners: xlim = list(plt.gca().get_xlim()) ylim = list(plt.gca().get_ylim()) x = (self.x_old - event.x) / (1. * self.canvas.window.get_size()[0] / (xlim[1] - xlim[0])) y = (event.y - self.y_old) / (1. * self.canvas.window.get_size()[1] / (ylim[1] - ylim[0])) self.x_old = event.x self.y_old = event.y self.axes_move(x, y, x, y) self.do_refresh() def refresh(self): """refresh function. This function is call periodically by do_refresh""" self.bRefresh = True def do_refresh(self): """Update the graph if bRefresh is True""" if self.bRefresh: self.bRefresh = False self.canvas.draw() gtk.timeout_add(30, self.refresh) def on_release(self, widget, event): """Event listener : release""" self.press = False def on_scroll(self, widget, event): """Event listener : scroll. Update zoom""" if event.direction == 0 and self.adjustement.get_value() < 99: self.adjustement.set_value(self.adjustement.get_value() + 1) elif event.direction == 1 and self.adjustement.get_value() > 0: self.adjustement.set_value(self.adjustement.get_value() - 1) def on_zoom_changed(self, widget): """Event listerner : HScale change. Update zoom""" if self.corners: im = None if self.bg_img: im = self.bg_img.get_children()[0] if widget.value != 0: zoom = (self.zoom_value - widget.value) * (self.corners[1][0] - self.corners[0][0]) / 200 self.axes_zoom(-zoom, -zoom, zoom, zoom) if im: dim = min(1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data'])) corners = min(self.corners[1][0] - self.corners[0][0], self.corners[1][1] - self.corners[0][1]) im.set_zoom(im.get_zoom() - zoom * 2 * dim / corners) else: plt.gca().set_xlim((self.corners[0][0], self.corners[1][0])) plt.gca().set_ylim((self.corners[0][1], self.corners[1][1])) if im: im.set_zoom(min(1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data']))) self.zoom_value = widget.value self.do_refresh() def on_lose_focus(self, widget, event): """Event listener : focus""" self.press = False NetworkGraph.NetworkGraph().node_click = False for node in NetworkGraph.NetworkGraph().graph.nodes(data=True): node[1]['object'].press = False for edge in NetworkGraph.NetworkGraph().graph.edges(data=True): edge[2]['object'].press = False self.do_refresh() def on_redraw(self, widget): """Event listener : button redraw""" self.draw() def axes_move(self, x0, y0, x1, y1): """Change axis position according to the drawing area limit. Parameters ---------- x0 : float. x minimal value x1 : float. x maximal value y0 : float. y minimal value y1 : float. y maximal value """ if self.corners: x = list(plt.gca().get_xlim()) y = list(plt.gca().get_ylim()) if ((x0 < 0 and x[0] + x0 >= self.corners[0][0]) or (x0 > 0 and x[0] + x0 < x[1])) and \ ((x1 > 0 and x[1] + x1 <= self.corners[1][0]) or (x1 < 0 and x[1] + x1 > x[0])): x[0] += x0 x[1] += x1 if ((y0 < 0 and y[0] + y0 >= self.corners[0][1]) or (y0 > 0 and y[0] + y0 < y[1])) and \ ((y1 > 0 and y[1] + y1 <= self.corners[1][1]) or (y1 < 0 and y[1] + y1 > y[0])): y[0] += y0 y[1] += y1 plt.gca().set_xlim((x[0], x[1])) plt.gca().set_ylim((y[0], y[1])) def axes_zoom(self, x0, y0, x1, y1): """Zoom axis position according to the drawing area limit. Parameters ---------- x0 : float. x minimal value x1 : float. x maximal value y0 : float. y minimal value y1 : float. y maximal value """ if self.corners: x = list(plt.gca().get_xlim()) y = list(plt.gca().get_ylim()) if (x0 < 0 and x[0] >= self.corners[0][0]) or (x0 > 0 and x[0] + x0 < x[1]): x[0] += x0 if (x1 > 0 and x[1] <= self.corners[1][0]) or (x1 < 0 and x[1] - x1 > x[0]): x[1] += x1 if (y0 < 0 and y[0] >= self.corners[0][1]) or (y0 > 0 and y[0] + y0 < y[1]): y[0] += y0 if (y1 > 0 and y[1] <= self.corners[1][1]) or (y1 < 0 and y[1] - y1 > y[0]): y[1] += y1 plt.gca().set_xlim((x[0], x[1])) plt.gca().set_ylim((y[0], y[1])) def background_image(self, file): """Set the file image as background image""" if self.bg_img: self.bg_img.remove() datafile = get_sample_data(file) img = plt.imread(datafile) im = OffsetImage(img) im.set_zoom(min(1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data']))) self.bg_img = AnnotationBbox(im, (0.5, 0.5), xycoords='data', frameon=False) self.bg_img.set_zorder(-1) plt.gca().add_artist(self.bg_img) self.do_refresh() def draw(self): """Draw the netowrk graph and set limit corners""" g = NetworkGraph.NetworkGraph() g.layout_graph() g.draw(self.canvas) self.corners = (-0.05, -0.05), (1.05, 1.05) plt.gca().set_xlim((-0.05, 1.05)) plt.gca().set_ylim((-0.05, 1.05)) self.do_refresh()