Diagrama de dispersión con texto diferente en cada punto de datos

Resuelto Labibah asked hace 11 años • 9 respuestas

Estoy intentando hacer un diagrama de dispersión y anotar puntos de datos con diferentes números de una lista. Entonces, por ejemplo, quiero trazar yvs xy anotar con los números correspondientes de n.

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
x = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]
ax = fig.add_subplot(111)
ax1.scatter(z, y, fmt='o')

¿Algunas ideas?

Labibah avatar Jan 21 '13 11:01 Labibah
Aceptado

No conozco ningún método de trazado que requiera matrices o listas, pero podría usarlo annotate()mientras itera sobre los valores en n.

import matplotlib.pyplot as plt
x = [0.15, 0.3, 0.45, 0.6, 0.75]
y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()
ax.scatter(x, y)

for i, txt in enumerate(n):
    ax.annotate(txt, (x[i], y[i]))

Hay muchas opciones de formato annotate(), consulte el sitio web de matplotlib:

ingrese la descripción de la imagen aquí

Rutger Kassies avatar Jan 21 '2013 07:01 Rutger Kassies

En caso de que alguien esté intentando aplicar las soluciones anteriores a a .scatter()en lugar de a .subplot(),

Intenté ejecutar el siguiente código

import matplotlib.pyplot as plt
x = [0.15, 0.3, 0.45, 0.6, 0.75]
y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
n = [58, 651, 393, 203, 123]

fig, ax = plt.scatter(x, y)

for i, txt in enumerate(n):
    ax.annotate(txt, (x[i], y[i]))

Pero encontré errores que indicaban "no se puede descomprimir el objeto PathCollection no iterable", y el error apunta específicamente a la línea de código fig, ax = plt.scatter(x, y)

Finalmente resolví el error usando el siguiente código

import matplotlib.pyplot as plt
plt.scatter(x, y)

for i, txt in enumerate(n):
    plt.annotate(txt, (x[i], y[i]))

No esperaba que hubiera una diferencia entre ellos .scatter()y .subplot() debería haberlo sabido mejor.

Heather Claxton avatar Mar 28 '2019 02:03 Heather Claxton

En versiones anteriores a matplotlib 2.0, ax.scatterno es necesario trazar texto sin marcadores. En la versión 2.0 necesitarás ax.scatterconfigurar el rango y los marcadores adecuados para el texto.

import matplotlib.pyplot as plt
y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()

for i, txt in enumerate(n):
    ax.annotate(txt, (z[i], y[i]))

Y en este enlace podéis encontrar un ejemplo en 3d.

rafaelvalle avatar May 15 '2016 19:05 rafaelvalle

También puedes utilizar pyplot.text(ver aquí ).

def plot_embeddings(M_reduced, word2Ind, words):
    """ 
        Plot in a scatterplot the embeddings of the words specified in the list "words".
        Include a label next to each point.
    """
    for word in words:
        x, y = M_reduced[word2Ind[word]]
        plt.scatter(x, y, marker='x', color='red')
        plt.text(x+.03, y+.03, word, fontsize=9)
    plt.show()

M_reduced_plot_test = np.array([[1, 1], [-1, -1], [1, -1], [-1, 1], [0, 0]])
word2Ind_plot_test = {'test1': 0, 'test2': 1, 'test3': 2, 'test4': 3, 'test5': 4}
words = ['test1', 'test2', 'test3', 'test4', 'test5']
plot_embeddings(M_reduced_plot_test, word2Ind_plot_test, words)

ingrese la descripción de la imagen aquí

irudyak avatar Jan 24 '2019 14:01 irudyak

Me encantaría agregar que incluso puedes usar flechas/cuadros de texto para anotar las etiquetas. Esto es lo que quiero decir:

import random
import matplotlib.pyplot as plt


y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()
ax.scatter(z, y)

ax.annotate(n[0], (z[0], y[0]), xytext=(z[0]+0.05, y[0]+0.3), 
    arrowprops=dict(facecolor='red', shrink=0.05))

ax.annotate(n[1], (z[1], y[1]), xytext=(z[1]-0.05, y[1]-0.3), 
    arrowprops = dict(  arrowstyle="->",
                        connectionstyle="angle3,angleA=0,angleB=-90"))

ax.annotate(n[2], (z[2], y[2]), xytext=(z[2]-0.05, y[2]-0.3), 
    arrowprops = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1))

ax.annotate(n[3], (z[3], y[3]), xytext=(z[3]+0.05, y[3]-0.2), 
    arrowprops = dict(arrowstyle="fancy"))

ax.annotate(n[4], (z[4], y[4]), xytext=(z[4]-0.1, y[4]-0.2),
    bbox=dict(boxstyle="round", alpha=0.1), 
    arrowprops = dict(arrowstyle="simple"))

plt.show()

Lo cual generará el siguiente gráfico: ingrese la descripción de la imagen aquí

Anwarvic avatar May 19 '2020 21:05 Anwarvic