gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:08:40 24 4
gpt4 key购买 nike

当我点击其图例标签时,任何人都可以帮助如何更改 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()

关于python - 单击图例时如何更改 matplot 中一组点的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56784706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com