Skip to main content
 首页 » 编程设计

python之单击图例时如何更改 matplot 中一组点的颜色

2024年11月24日752php

当我点击其图例标签时,任何人都可以帮助如何更改 pyplot 中一组点的颜色?

下面是一段代码,其中有两组点 x1 和 x2。我将它们绘制成散点图。它以蓝色绘制集合 x1 和 x2 中的所有点。当我点击图例 x1 标签时,有没有办法将集合 x1 中的点的颜色更改为红色

import matplotlib.pyplot as plot 
x1 = [1,3,5,7,9] 
x2 = [2,4,6,8,10] 
fig, ax = plot.subplots() 
ax.scatter(x1,x1,color = 'b',s = 50,label = 'x1') 
ax.scatter(x2,x2,color = 'b',s = 50,label = 'x2') 
ax.legend(loc = 'upper left') 
plot.show() 

请您参考如下方法:

matplotlib 文档中有一个关于 legend picking 的例子.我们可能会对其进行调整,以适应散点上发生拾取并且颜色要发生变化的情况。

为此,我们在传奇艺术家(代理)上创建了一个选择器并附加了一个属性 toggled to 是要知道艺术家处于两种状态中的哪一种(这比使用 get_color 更容易,因为颜色在内部转换为 RGB 元组)。

import matplotlib.pyplot as plt 
 
 
x1 = [1,3,5,7,9] 
x2 = [2,4,6,8,10] 
fig, ax = plt.subplots() 
line1 = ax.scatter(x1,x1,color = 'b',s = 50,label = 'x1') 
line2 = ax.scatter(x2,x2,color = 'b',s = 50,label = 'x2') 
leg = ax.legend(loc = 'upper left') 
 
# we will set up a dict mapping legend line to orig line, and enable 
# picking on the legend line 
lines = [line1, line2] 
lined = dict() 
for legline, origline in zip(leg.legendHandles, lines): 
    legline.set_picker(5)  # 5 pts tolerance 
    legline.toggled = False  # create custom attribute to observe state 
    lined[legline] = origline 
 
def onpick(event): 
    legline = event.artist 
    origline = lined[legline] 
 
    c = "b" if legline.toggled else "r" 
    legline.set_color(c) 
    origline.set_color(c) 
 
    fig.canvas.draw_idle() 
 
    legline.toggled = not legline.toggled 
 
 
fig.canvas.mpl_connect('pick_event', onpick) 
 
plt.show()