用networkx制作一个可单击的图形

2024-05-14 12:58:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python生成一个图形的可单击图像。 我一开始直接打电话给graphviz,后来发现了networkxhttp://networkx.lanl.gov。在

我想让我的程序获得关于哪个节点显示在(x,y)坐标处的信息,用户单击图形的位置。 我想我可以使用pyplot窗口来打开并显示图形,使用鼠标单击时的(x,y)坐标,但是我需要某种图像映射来知道是哪个 节点已在该坐标处可视化!在

你能告诉我这件事能不能/怎样做?在


Tags: 用户图像程序networkx信息图形节点可视化
1条回答
网友
1楼 · 发布于 2024-05-14 12:58:13

多亏了http://groups.google.com/group/networkx-discuss的好心人,我解决了这个问题 (http://groups.google.com/group/networkx-discuss/browse_thread/thread/aac227e1fb2a4719):

下面的(部分)代码在Tkinter中工作,允许创建一个包含networkx图形的matplotlib窗口(顺便说一下,是非阻塞的),并在单击给定节点时执行visitNode()过程。在

import networkx as nx 
import matplotlib.pyplot as plt 
import pylab

class AnnoteFinder:  # thanks to http://www.scipy.org/Cookbook/Matplotlib/Interactive_Plotting
    """
    callback for matplotlib to visit a node (display an annotation) when points are clicked on.  The
    point which is closest to the click and within xtol and ytol is identified.
    """
    def __init__(self, xdata, ydata, annotes, axis=None, xtol=None, ytol=None):
        self.data = zip(xdata, ydata, annotes)
        if xtol is None: xtol = ((max(xdata) - min(xdata))/float(len(xdata)))/2
        if ytol is None: ytol = ((max(ydata) - min(ydata))/float(len(ydata)))/2
        self.xtol = xtol
        self.ytol = ytol
        if axis is None: axis = pylab.gca()
        self.axis= axis
        self.drawnAnnotations = {}
        self.links = []

    def __call__(self, event):
        if event.inaxes:
            clickX = event.xdata
            clickY = event.ydata
            if self.axis is None or self.axis==event.inaxes:
                annotes = []
                for x,y,a in self.data:
                    if  clickX-self.xtol < x < clickX+self.xtol and  clickY-self.ytol < y < clickY+self.ytol :
                        dx,dy=x-clickX,y-clickY
                        annotes.append((dx*dx+dy*dy,x,y, a) )
                if annotes:
                    annotes.sort() # to select the nearest node
                    distance, x, y, annote = annotes[0]
                    self.visitNode(annote)

    def visitNode(self, annote): # Visit the selected node
        # do something with the annote value
        print "visitNode", annote

fig = plt.figure() ax = fig.add_subplot(111) ax.set_title('select nodes to navigate there')

G=nx.MultiDiGraph()  # directed graph G = nx.wheel_graph(5)

pos=nx.spring_layout(G) # the layout gives us the nodes position x,y,annotes=[],[],[] for key in pos:
    d=pos[key]
    annotes.append(key)
    x.append(d[0])
    y.append(d[1]) nx.draw(G,pos,font_size=8)

af =  AnnoteFinder(x,y, annotes) fig.canvas.mpl_connect('button_press_event', af)

plt.show()

相关问题 更多 >

    热门问题