Python,Matplotlib,Scatter plot,更改点击点上的颜色

时间:2015-10-05 10:07:13

标签: python matplotlib plot

所以我有一个简单的散点图,有一个选择器事件。我想用鼠标更改我点击的数据点的颜色。我的代码将改变整个数组的颜色。我怎样才能改变一个特定点?感谢

import sys
import numpy as np
import matplotlib.pyplot as plt    
testData = np.array([[0,0], [0.1, 0], [0, 0.3], [-0.4, 0], [0, -0.5]])
    fig, ax = plt.subplots()
    sctPlot, = ax.plot(testData[:,0], testData[:,1], "o", picker = 5)
    plt.grid(True)
    plt.axis([-0.5, 0.5, -0.5, 0.5])

def on_pick(event):
    artist = event.artist
    artist.set_color(np.random.random(3))
    print "click!"
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)

1 个答案:

答案 0 :(得分:6)

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

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))
plt.grid(True)
plt.axis([-0.5, 0.5, -0.5, 0.5])

def on_pick(event):
    print testData[event.ind], "clicked"
    coll._facecolors[event.ind,:] = (1, 0, 0, 1)
    coll._edgecolors[event.ind,:] = (1, 0, 0, 1)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()