使用matplotlib将networkx图嵌入到wxPython中

时间:2012-07-31 09:37:26

标签: python matplotlib wxpython networkx

我用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()

有人可以给我一个提示吗?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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()