3

我用networkx创建了一个图表。

G=nx.DiGraph()

# ... building the graph ...
# and I can display it with matplotlib like this:

nx.draw(G)
matplotlib.pyplot.show()

但我想做的是,从以下示例开始,将创建的图形嵌入到 wxPython 中。一开始我只想打印它;根本没有用户交互。

from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure

import wx

class CanvasPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

    def draw(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s)


if __name__ == "__main__":
    app = wx.PySimpleApp()
    fr = wx.Frame(None, title='test')
    panel = CanvasPanel(fr)
    panel.draw()
    fr.Show()
    app.MainLoop()

有人可以给我小费吗?

4

2 回答 2

1

在这里我所做的,您可以使用 plt.figure() 获取图形的实例并将其粘贴到画布中,然后使用例如 vbox 将画布添加到面板:

import matplotlib.pyplot as plt
import networkx as nx
import wx
from matplotlib.backends.backend_wxagg import \
FigureCanvasWxAgg as FigCanvas, \
NavigationToolbar2WxAgg as NavigationToolbar

class NetworkFrame(wx.Frame):

def __init__(self):
    wx.Frame.__init__(self, None, -1)
    self.panel = wx.Panel(self)
    self.fig = plt.figure()
    self.canvas = FigCanvas(self.panel, -1, self.fig)
    G=nx.house_graph()
pos={0:(0,0),
    1:(1,0),
    2:(0,1),
    3:(1,1),
    4:(0.5,2.0)}

nx.draw_networkx_nodes(G,pos,node_size=2000,nodelist=[4])
nx.draw_networkx_nodes(G,pos,node_size=3000,nodelist=[0,1,2,3],node_color='b')
nx.draw_networkx_edges(G,pos,alpha=0.5,width=6)
plt.axis('off')
self.vbox = wx.BoxSizer(wx.VERTICAL)
    self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
    self.toolbar = NavigationToolbar(self.canvas)
    self.vbox.Add(self.toolbar, 0, wx.EXPAND)
    self.panel.SetSizer(self.vbox)
    self.vbox.Fit(self)


#plt.savefig("house_with_colors.png") # save as png
#plt.show() # display

if __name__ == '__main__':
  app = wx.PySimpleApp()
  app.frame = NetworkFrame()
  app.frame.Show()
  app.MainLoop()
于 2013-02-07T17:04:07.950 回答
1

解决方法:将 networkx 图形导出为 png 并使用 imread 绘制它。

plt.axis("off") # turn off axis
# output to a temporary file name and display it in matplotlib     
filename = "/tmp/image.png"
plt.savefig(filename, dpi=400, bbox_inches='tight') 
img = imread(filename)
self.axes.imshow(img)
于 2012-09-01T12:03:15.087 回答