pyqtgraph github repo의 this 예제를 찾았습니다.pyqtgraph는 노드의 텍스트를 가져오고 MouseClick의 색상을 변경합니다.
나는 다음과 같은 기능을 pyqtgraph
와 상호 작용 (네트워크) 그래프를 만들 싶습니다 : 사용자가 노드를 클릭하면
- , 그/그녀가 의 'text'-정보를 얻을 것이다 마디.
- 는 노드는
- 여러 선택
코드를 허용 (예 : 노란색) 변경됩니다 해당 노드의 색상뿐만 아니라 모든 이웃 (가장자리와 노드)의 을 클릭 한 경우 :
:
# -*- coding: utf-8 -*-
"""
Simple example of subclassing GraphItem.
"""
import initExample ## Add path to library (just for examples; you do not need this)
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)
w = pg.GraphicsWindow()
w.setWindowTitle('pyqtgraph example: CustomGraphItem')
v = w.addViewBox()
v.setAspectLocked()
class Graph(pg.GraphItem):
def __init__(self):
self.dragPoint = None
self.dragOffset = None
self.textItems = []
pg.GraphItem.__init__(self)
self.scatter.sigClicked.connect(self.clicked)
def setData(self, **kwds):
self.text = kwds.pop('text', [])
self.data = kwds
if 'pos' in self.data:
npts = self.data['pos'].shape[0]
self.data['data'] = np.empty(npts, dtype=[('index', int)])
self.data['data']['index'] = np.arange(npts)
self.setTexts(self.text)
self.updateGraph()
def setTexts(self, text):
for i in self.textItems:
i.scene().removeItem(i)
self.textItems = []
for t in text:
item = pg.TextItem(t)
self.textItems.append(item)
item.setParentItem(self)
def updateGraph(self):
pg.GraphItem.setData(self, **self.data)
for i,item in enumerate(self.textItems):
item.setPos(*self.data['pos'][i])
def mouseDragEvent(self, ev):
if ev.button() != QtCore.Qt.LeftButton:
ev.ignore()
return
if ev.isStart():
# We are already one step into the drag.
# Find the point(s) at the mouse cursor when the button was first
# pressed:
pos = ev.buttonDownPos()
pts = self.scatter.pointsAt(pos)
if len(pts) == 0:
ev.ignore()
return
self.dragPoint = pts[0]
ind = pts[0].data()[0]
self.dragOffset = self.data['pos'][ind] - pos
elif ev.isFinish():
self.dragPoint = None
return
else:
if self.dragPoint is None:
ev.ignore()
return
ind = self.dragPoint.data()[0]
self.data['pos'][ind] = ev.pos() + self.dragOffset
self.updateGraph()
ev.accept()
def clicked(self, pts):
print("clicked: %s" % pts)
g = Graph()
v.addItem(g)
## Define positions of nodes
pos = np.array([
[0,0],
[10,0],
[0,10],
[10,10],
[5,5],
[15,5]
], dtype=float)
## Define the set of connections in the graph
adj = np.array([
[0,1],
[1,3],
[3,2],
[2,0],
[1,5],
[3,5],
])
## Define the symbol to use for each node (this is optional)
symbols = ['o','o','o','o','t','+']
## Define the line style for each connection (this is optional)
lines = np.array([
(255,0,0,255,1),
(255,0,255,255,2),
(255,0,255,255,3),
(255,255,0,255,2),
(255,0,0,255,1),
(255,255,255,255,4),
], dtype=[('red',np.ubyte),('green',np.ubyte),('blue',np.ubyte),('alpha',np.ubyte),('width',float)])
## Define text to show next to each symbol
texts = ["Point %d" % i for i in range(6)]
## Update the graph
g.setData(pos=pos, adj=adj, pen=lines, size=1, symbol=symbols, pxMode=False, text=texts)
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
위의 코드는 노드를 클릭 할 때 다음과 같은 정보를 반환
실제로 전체 그래프 항목입니다 (클릭 신호가 전체 그래프에서 호출되기 때문에).
Now : 모든 노드에서 MouseClicking 기능을 호출하고 해당 노드의 텍스트를 가져 와서 해당 클릭 이벤트에서 해당 (및 이웃) 색을 변경하려면 어떻게해야합니까?
Another example은 다른 플롯에서 클릭 된 곡선의 색상을 변경하는 것을 보여줍니다. 여기에서 클릭 신호는 모든 곡선에서 호출됩니다. 이 코드를 첫 번째 언급 된 코드 예제에서 비슷한 것을 구현하기위한 시작점으로 사용하려고 시도했지만 솔직히 pyqtgraph 그래프 객체에서 단일 노드를 얻는 방법을 모르겠습니다. ] 노드는 위치를 통해서만 정의됩니다.
언제나처럼 여기에 도움을 주시면 감사하겠습니다.
편집 :
def clicked(self, scatter, pts):
data_list = scatter.data.tolist()
mypoint = [tup for tup in data_list if pts[0] in tup][0]
mypoint_index = data_list.index(mypoint)
mypoint_text = self.text[mypoint_index]
편집 II :
의 더 정교한 예를 들어 감사의 kesumu하는 대답은,이 같은 클릭 된 노드의 텍스트 내용을 얻을 수있었습니다 동일한 문제는 here에서 찾을 수 있습니다.
kesumu, 정말 고마워요, 정말 도움이 됐어요! 클릭 한 노드와 텍스트를 가져올 수 있습니다. 텍스트를 가져 오는 방법에 대해 질문을 편집 할 수 있습니다. 하지만 이제는 클릭 한 노드와 이웃 노드의 색상을 변경하는 방법에 익숙해졌습니다.이 질문의 주요 관심사는 실제로 클릭 된 노드와 텍스트 콘텐츠를 얻는 것이 었습니다. . 다시 : 감사합니다! – dliv