[英]How to pick a set of lines instead of just a single line?
我正在使用Matplolib的Line2D繪制多條線,並希望一次選擇或選擇所有線。
MWE提供的功能是繪制三角形(可以是任何多邊形或形狀),並包括一個功能,該功能可以分別拾取每條線。 我想通過單擊選擇整個三角形。 另外,我注意到,如果我添加另一行,onPick函數根本無法使用。 有人知道我做錯了嗎?
編輯按照下面的注釋中的建議,我添加了一個Polygon和一個修改后的函數pick_simple()(來自: https ://matplotlib.org/3.1.0/gallery/event_handling/pick_event_demo.html)。 但是不幸的是,這帶來了新的問題。 通過繪制多邊形,即使我設置fill = False以及線寬和顏色,我也會得到一個填充的藍色補丁。 而且pick_simple()函數沒有做任何讓我感到困惑的事情。
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
fig = plt.figure()
ax = fig.add_subplot(111)
triangle = [[0.1, 0.3],
[0.2, 0.8],
[0.3, 0.5],
[0.1, 0.3]]
for i in range(len(triangle)-1):
tri = Line2D([triangle[i][0],triangle[i+1][0]],[triangle[i][1],
triangle[i+1][1]], linewidth=0.75, color='#F97306')
tri.set_picker(True)
ax.add_line(tri)
geometry = [[0.0,0.0],[0.1,0.05],[0.2,0.15],[0.3,0.20],[0.4,0.25],[0.5,0.30],
[0.6,0.25],[0.7,0.15],[0.8,0.05],[0.9,0.025],[1.0,0.0]]
patches = []
polygon = Polygon(geometry, closed=False, fill=False, linewidth=0.75, color='#F97306')
polygon.set_picker(True)
patches.append(polygon)
p = PatchCollection(patches)
ax.add_collection(p)
plt.show()
def pick_simple():
def onpick(event):
if isinstance(event.artist, Polygon):
patch = event.artist
print('onpick patch:', patch.get_path())
fig.canvas.mpl_connect('pick_event', onpick)
def pick_factory(ax):
def onPick(event):
if event.inaxes == ax:
for line in ax.lines:
if line.get_picker():
cont, ind = line.contains(event)
if cont:
line.set_color('#029386')
line.set_linewidth(5)
ax.figure.canvas.draw_idle()
fig = ax.get_figure() # get the figure of interest
fig.canvas.mpl_connect('button_press_event', onPick)
pick_factory(ax)
pick_simple()
有幾個較小的錯誤。
event.ind
選擇被選擇的集合的成員。 PatchCollection
的目的通常是設置其子級本身的屬性,如線寬,顏色等。 如果您不想這樣做,則需要使用match_original=True
完整的代碼:
from matplotlib import pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
fig = plt.figure()
ax = fig.add_subplot(111)
geometry = [[0.0,0.0],[0.1,0.05],[0.2,0.15],[0.3,0.20],[0.4,0.25],[0.5,0.30],
[0.6,0.25],[0.7,0.15],[0.8,0.05],[0.9,0.025],[1.0,0.0]]
patches = []
polygon = Polygon(geometry, closed=False, fill=False, linewidth=3, color='#F97306')
patches.append(polygon)
p = PatchCollection(patches, match_original=True)
p.set_picker(True)
ax.add_collection(p)
def pick_simple():
def onpick(event):
if isinstance(event.artist, PatchCollection):
collection = event.artist
print('onpick collection:', collection)
print('picked index', event.ind)
print('path at index', collection.get_paths()[event.ind[0]])
return fig.canvas.mpl_connect('pick_event', onpick)
cid = pick_simple()
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.