Plotting directed graphs in Python in a way that show all edges separately

前端 未结 4 1733
Happy的楠姐
Happy的楠姐 2020-12-01 04:44

I\'m using Python to simulate a process that takes place on directed graphs. I would like to produce an animation of this process.

The problem that I\'ve run into i

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 05:04

    Using NetworkX, a possible workaround which avoids file I/O and uses dot via pydot for layout is:

    import networkx as nx
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    from io import BytesIO
    
    g = nx.dodecahedral_graph()
    d = nx.drawing.nx_pydot.to_pydot(g) # d is a pydot graph object, dot options can be easily set
    # attributes get converted from networkx,
    # use set methods to control dot attributes after creation
    
    png_str = d.create_png()
    sio = BytesIO() # file-like string, appropriate for imread below
    sio.write(png_str)
    sio.seek(0)
    
    img = mpimg.imread(sio)
    imgplot = plt.imshow(img)
    

    for why seek(0) is needed, see How to create an image from a string in python

    If within IPython (qt)console, then the above will print inline and a more direct approach is:

    import networkx as nx
    from IPython.display import Image
    
    g = nx.dodecahedral_graph()
    d = nx.drawing.nx_pydot.to_pydot(g)
    
    png_str = d.create_png()
    Image(data=png_str)
    

提交回复
热议问题