保存nxpd生成的图形图

时间:2017-06-13 20:50:58

标签: python networkx

关于nxpd的文档非常清楚如何打印ipython内部的图形,但是如何将图形保存为.png或.pdf?下面的方法读入包含状态变化概率的数据帧(mc)和保存绘制图形的输出路径。我不清楚如何将nxpd绘图传递给pyplot或使用内部保存方法。

NXPD文档有限:https://github.com/chebee7i/nxpd

def DrawMarkov(mc, outputPath):
    import matplotlib.pyplot as plt
    from pandas import DataFrame
    import networkx as nx
    from nxpd import draw
    ## Draw as an internal to ipython
    # draw(G, show='ipynb')
    ## OR
    # from nxpd import nxpdParams
    # nxpdParams['show'] = 'ipynb' 

    def Add_Nodes(G, name):
        for node in range(0,len(mc) ):
    #         print(node); print(type(node)); print(color_map[node])
            G.add_node(node, style='filled', fillcolor=color_map[node], )

    def Add_Edges(G,mc):
        for start in range(0,len(mc[0])):
            # print(start,'\n')
            for finish in range(0,len(mc) ):
                # print(mc[start][finish])
                if mc[start][finish]!=0:
                    G.add_edge(start, finish, weight=mc[start][finish], label=str(mc[start][finish]) )

    color_map = {0: 'lightblue', 
                 1:'palegreen', 
                 2:'lightcoral'}

    ## Plot DiGraph
    G = nx.DiGraph()  
    Add_Nodes(G,mc)  
    Add_Edges(G,mc)  
    mapping={0:'State1', 1:'State2', 2:'State3'}
    G = nx.relabel_nodes(G,mapping)  

    ## Output  
    draw(G, layout='dot')  # , show='ipynb'  # unclear how to pass graph to plt
    # plt.savefig(os.path.join(outputPath, 'Graph.png') )  

1 个答案:

答案 0 :(得分:1)

您可以在绘图功能中指定保存格式。有关详细信息,请查看实施https://github.com/chebee7i/nxpd/blob/master/nxpd/nx_pydot.py

用法:

draw(G, format ='pdf')

支持的格式包括:

'canon', 'cmap', 'cmapx', 'cmapx_np', 'dia', 'dot',
'fig', 'gd', 'gd2', 'gif', 'hpgl', 'imap', 'imap_np',
'ismap', 'jpe', 'jpeg', 'jpg', 'mif', 'mp', 'pcl', 'pdf',
'pic', 'plain', 'plain-ext', 'png', 'ps', 'ps2', 'svg',
'svgz', 'vml', 'vmlz', 'vrml', 'vtx', 'wbmp', 'xdot', 'xlib'