Search code examples
pythongraphnetworkxpyvis

How to display graph in Pyvis more clearly?


I want to visualize a graph in Pyvis which its nodes has labels. I am completely able to visualize it in Pyvis but my problem is about the ways of visualizing it. The graph displayed in Pyvis is not clear and edges are messed up. Is there any way to visualize the graph more clear? The image below shows the graph. enter image description here

For example in the graph, node 15 is displayed well. I want other nodes to be displayed in a clear way that the connections can be displayed more clearly

Update: This is the code i use for drawing graph using Pyvis:

    def showGraph(FileName, labelList):

        Txtfile = open("./results.txt")
        G = nx.read_weighted_edgelist(Txtfile)
        Txtfile.close()

        palette = (sns.color_palette("Pastel1", n_colors=len(set(labelList.values())))) 
        palette = palette.as_hex()
        colorDict = {}
        counter = 0
        for i in palette:
            colorDict[counter] = i
            counter += 1

        N = Network(height='100%', width='100%', directed=False, notebook=False)
        for n in G.nodes:
            N.add_node(n, color=(colorDict[labelList[n]]), size=5)
        for e in G.edges.data():
            N.add_edge(e[0], e[1], title=str(e[2]), value=e[2]['weight'])

        N.show('result.html')

results.txt is my edge list file and labelList holds label of each node. Labels are numerical. For example label of node 48 is 5, it can be anything. I use labels to give different colors to nodes.


Solution

  • The NetworkX circular layouts tend to make individual nodes and the connections between them easier to see, so you could try that as long as you don't want nodes to move (without dragging) after you've drawn them.

    Before creating your pyvis network, run the following on your NetworkX graph to create a dictionary that will be keyed by node and have (x, y) positions as values. You might need to mess around with the scale parameter a bit to see what works best for you.

    pos = nx.circular_layout(G, scale = 1000)
    

    You can then add x and y values from pos to your pyvis network when you add each node. Adding physics = False keeps the nodes in one place unless you click and drag them around.

    for n in G.nodes:
        N.add_node(n, 
            color=(colorDict[labelList[n]]),
            size=5,
            x = pos[n][0],
            y = pos[n][1],
            physics = False)
    

    I'm not sure how the edge weights will play into things, so you should probably also add physics = False to the add_edge parameters to ensure that nothing will move.

    Since I didn't have your original data, I just generated a random graph with 10 nodes and this was the result in pyvis.

    pyvis circular network