Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

562
Vistas
Python muestra la imagen al pasar el mouse sobre un punto

Tengo un gráfico de dispersión de puntos en 2 dimensiones, que corresponden a imágenes. Me preguntaba si hay una manera fácil de mostrar la imagen correspondiente (como una ventana emergente o información sobre herramientas) cuando pasa el mouse sobre cada punto. Lo intenté de manera gráfica, pero descubrí que necesita editar manualmente JavaScript para que funcione el evento de desplazamiento. ¿Existe una solución simple solo con matplotlib o algún otro paquete común?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Encuentre aquí una solución completa sobre cómo mostrar una imagen en eventos de desplazamiento. Utiliza un 'motion_notify_event' para detectar cuando el mouse está sobre un punto de dispersión (flotando). Si este es el caso, muestra una anotación de imagen con una imagen correspondiente al lado del punto de dispersión flotante.

 import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox import numpy as np; np.random.seed(42) # Generate data x, y for scatter and an array of images. x = np.arange(20) y = np.random.rand(len(x)) arr = np.empty((len(x),10,10)) for i in range(len(x)): f = np.random.rand(5,5) arr[i, 0:5,0:5] = f arr[i, 5:,0:5] =np.flipud(f) arr[i, 5:,5:] =np.fliplr(np.flipud(f)) arr[i, 0:5:,5:] = np.fliplr(f) # create figure and plot scatter fig = plt.figure() ax = fig.add_subplot(111) line, = ax.plot(x,y, ls="", marker="o") # create the annotations box im = OffsetImage(arr[0,:,:], zoom=5) xybox=(50., 50.) ab = AnnotationBbox(im, (0,0), xybox=xybox, xycoords='data', boxcoords="offset points", pad=0.3, arrowprops=dict(arrowstyle="->")) # add it to the axes and make it invisible ax.add_artist(ab) ab.set_visible(False) def hover(event): # if the mouse is over the scatter points if line.contains(event)[0]: # find out the index within the array from the event ind, = line.contains(event)[1]["ind"] # get the figure size w,h = fig.get_size_inches()*fig.dpi ws = (event.x > w/2.)*-1 + (event.x <= w/2.) hs = (event.y > h/2.)*-1 + (event.y <= h/2.) # if event occurs in the top or right quadrant of the figure, # change the annotation box position relative to mouse. ab.xybox = (xybox[0]*ws, xybox[1]*hs) # make annotation box visible ab.set_visible(True) # place it at the position of the hovered scatter point ab.xy =(x[ind], y[ind]) # set the image corresponding to that point im.set_data(arr[ind,:,:]) else: #if the mouse is not over a scatter point ab.set_visible(False) fig.canvas.draw_idle() # add callback for mouse moves fig.canvas.mpl_connect('motion_notify_event', hover) plt.show()

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo Denunciar

0

Si desea que sus imágenes se muestren en RGB, debe ajustar ligeramente el código. Para este ejemplo, las imágenes deben estar en su disco. En lugar de usar un 3darray para las imágenes donde la primera dimensión solo representa el índice, necesita leer la imagen con plt.imread y luego establecer_data en la posición correspondiente en su matriz que contiene los nombres de las imágenes.

 import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox import numpy as np; np.random.seed(42) import os os.chdir('Path/to/your/images') # Generate data x, y for scatter and an array of images. x = np.arange(3) y = np.random.rand(len(x)) jpg_name_np = np.array(['904646.jpg', '903825.jpg', '905722.jpg']).astype('<U12') # names of your images files cmap = plt.cm.RdYlGn # create figure and plot scatter fig = plt.figure() ax = fig.add_subplot(111) #line, = ax.plot(x,y, ls="", marker="o") line = plt.scatter(x,y,c=heat, s=10, cmap=cmap) image_path = np.asarray(jpg_name_np) # create the annotations box image = plt.imread(image_path[0]) im = OffsetImage(image, zoom=0.1) xybox=(50., 50.) ab = AnnotationBbox(im, (0,0), xybox=xybox, xycoords='data', boxcoords="offset points", pad=0.3, arrowprops=dict(arrowstyle="->")) # add it to the axes and make it invisible ax.add_artist(ab) ab.set_visible(False) def hover(event): # if the mouse is over the scatter points if line.contains(event)[0]: # find out the index within the array from the event ind, = line.contains(event)[1]["ind"] # get the figure size w,h = fig.get_size_inches()*fig.dpi ws = (event.x > w/2.)*-1 + (event.x <= w/2.) hs = (event.y > h/2.)*-1 + (event.y <= h/2.) # if event occurs in the top or right quadrant of the figure, # change the annotation box position relative to mouse. ab.xybox = (xybox[0]*ws, xybox[1]*hs) # make annotation box visible ab.set_visible(True) # place it at the position of the hovered scatter point ab.xy =(x[ind], y[ind]) # set the image corresponding to that point im.set_data(plt.imread(image_path[ind])) else: #if the mouse is not over a scatter point ab.set_visible(False) fig.canvas.draw_idle() # add callback for mouse moves fig.canvas.mpl_connect('motion_notify_event', hover) fig = plt.gcf() fig.set_size_inches(10.5, 9.5) plt.show()

Trazar al pasar el cursor sobre el punto de dispersión

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda