[英]How to change the color of a set of points in matplot when clicked on the legends?
當我單擊其圖例標簽時,任何人都可以幫助如何更改 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 文檔中有一個關於圖例選擇的示例。 我們可以將它調整到在散點上發生拾取並且顏色要改變的情況。
為此,我們在圖例藝術家(代理)上創建了一個選擇器,並附加了一個toggled
到的屬性,以了解藝術家處於兩種狀態中的哪一種(這比使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.