Main

Retour vers le tutoriel complet

Interactions simples

Exemple de coloriage du nuage en fonction des clics

import sys
import numpy as np
import matplotlib.pyplot as plt

# définition du nuage
testData = np.array([[0,0], [0.1, 0], [0, 0.3], [-0.4, 0], [0, -0.5]])
fig, ax = plt.subplots()
coll = ax.scatter(testData[:,0], testData[:,1], color=["blue"]*len(testData), picker = 5, s=[50]*len(testData))
# aspects esthétiques facultatifs
plt.grid(True)
plt.axis([-0.5, 0.5, -0.5, 0.5])

# défintion du callback: interaction hyperfacile par variables globales !!!
def on_pick(event):
    print(testData[event.ind], "clicked") # récupération auto de l'élément cliqué
    coll._facecolors[event.ind,:] = (1, 0, 0, 1) # modif du plot
    coll._edgecolors[event.ind,:] = (1, 0, 0, 1)
    fig.canvas.draw()

# connection du système
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()

Interactions avancées avec mini-serveur


from matplotlib.pyplot import figure, show
import numpy as npy
from numpy.random import rand
import mpld3

x, y, c, s = rand(4, 100)


def onpick3(event):
    ind = event.ind
    print('onpick3 scatter:', ind, npy.take(x, ind), npy.take(y, ind))


fig = figure()
ax1 = fig.add_subplot(111)
col = ax1.scatter(x, y, 100 * s, c, picker=True)
# fig.savefig('pscoll.eps')
fig.canvas.mpl_connect('pick_event', onpick3)
show()

import matplotlib.pyplot as plt
import numpy as np
import mpld3

fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 100

scatter = ax.scatter(np.random.normal(size=N),
                     np.random.normal(size=N),
                     c=np.random.random(size=N),
                     s=1000 * np.random.random(size=N),
                     alpha=0.3,
                     cmap=plt.cm.jet)
ax.grid(color='white', linestyle='solid')

ax.set_title("Scatter Plot (with tooltips!)", size=20)

labels = ['point {0}'.format(i + 1) for i in range(N)]
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)

mpld3.show()