WestHealth / pyvis

Python package for creating and visualizing interactive network graphs.
http://pyvis.readthedocs.io/en/latest/
BSD 3-Clause "New" or "Revised" License
1k stars 172 forks source link

Centering Nodes #66

Open andrewlaikh opened 4 years ago

andrewlaikh commented 4 years ago

I was playing around with the API and was wondering if there is a way to center the node. In this toy example, I would like to center the node 'Joshua' but every time I reload the page, Joshua is in a different position. I have tried setting the x and y values when adding nodes but did not have success.

Is it possible to center nodes and if so, what am I doing wrong? Thanks.

from pyvis.network import Network
from pyvis import options
import pandas as pd

got_net = Network(height="500px", width="990px", directed=True)
# set the physics layout of the network
got_net.barnes_hut()
# got_data = pd.read_csv("https://www.macalester.edu/~abeverid/data/stormofswords.csv")
# print(got_net.toggle_stabilization(False))

data = [['tom', 'joshua', 1], ['nick' , 'joshua', 1], ['juli', 'tom', 1], ['joshua', 'tom', 1], ['juli', 'isiah', 1], ] 
got_data = pd.DataFrame(data, columns = ['Source', 'Target', 'Weight']) 

sources = got_data['Source']
targets = got_data['Target']
weights = got_data['Weight']

edge_data = zip(sources, targets, weights)

for e in edge_data:
    src = e[0]
    dst = e[1]
    w = e[2]

    # Use the below to set the edges for the color 
    if src!='joshua': 
      got_net.add_node(src, src, title=src, mass = 1) 
    else: 
      got_net.add_node(src, src, title=src, x = 500, y = 250, mass = 5) 
    if dst!='joshua':
      got_net.add_node(dst, dst, title=dst, mass=1)
    else: 
      got_net.add_node(dst, dst, title=dst, x = 500, y = 250, mass = 5)
    got_net.add_edge(src, dst, value=w, arrowStrikethrough = True)

neighbor_map = got_net.get_adj_list()

# add neighbor data to node hover data
for node in got_net.nodes:
    node["title"] += " Neighbors:<br>" + "<br>".join(neighbor_map[node["id"]])
    node["value"] = len(neighbor_map[node["id"]])

got_net.save_graph("gameofthrones.html")
nodes, edges, height, width, options = got_net.get_network_data()
maelfabien commented 4 years ago

I have a quite similar question, I'm looking for a way to set a seed when building a graph to preserve the same layout between 2 graphs. I haven't found in the code yet where to add this, I'm still looking

andrewlaikh commented 4 years ago

@maelfabien I figured that the 'issue' with the code above is that the x,y co-ordinates for **all nodes (not just one) needs to be explicitly included. Otherwise, the positions for all** nodes are not fixed.

boludo00 commented 4 years ago

@maelfabien While I have not experimented with this feature, the VisJS engine apparently can handle that out of the box.

This example demonstrates something similar to what you mentioned, and below is the JavaScript to accompany. It looks like simply supplyingrandomSeed attribute to the layout property of the options object does the trick.

  // create an array with nodes
  var nodes = new vis.DataSet([
    {id: 1, label: 'Node 1'},
    {id: 2, label: 'Node 2'},
    {id: 3, label: 'Node 3'},
    {id: 4, label: 'Node 4'},
    {id: 5, label: 'Node 5'}
  ]);

  // create an array with edges
  var edges = new vis.DataSet([
    {from: 1, to: 3},
    {from: 1, to: 2},
    {from: 2, to: 4},
    {from: 2, to: 5}
  ]);

  // create a network
  var container = document.getElementById('mynetwork');
  var data = {
    nodes: nodes,
    edges: edges
  };
  var options = {layout:{randomSeed:2}};
  var network = new vis.Network(container, data, options);

*EDIT: I just tried this in a notebook and it seems to work. It is a little awkward to modify the underlying options object of a pyvis network instance due to the current implementation of set_options but it'll do:

image image

I will leave this open since I want to rewrite the set_options method to be more user friendly and I could even add a method to support modifying the random seed directly through the network instance :)

boludo00 commented 4 years ago

Also, @andrewlaikh it could help to try and turn off the physics with toggle_physics(False) while supplying x and y coordinates to individual nodes. I am not sure how the VisJS physics engine handles the nodes on their end.

maelfabien commented 4 years ago

@boludo00 Thanks for your reply (and sorry for the late reply, I was on holiday). It looks like setting the random seed helps to produce the same graph twice, with similar node positions, when the nodes to plot are exactly the same. What I am currently struggling with is how to make two graphs with mostly similar edges, but some different ones, comparable. For example, I would like to make an explicit visual comparison of these two graphs:

Capture d’écran 2020-08-17 à 14 01 09 Capture d’écran 2020-08-17 à 14 01 31

Here's how I build them so far:

G = Network(notebook=True, height="500px", width="100%")
G.set_options('{"layout": {"randomSeed":5}}')

# looping here
...
    G.add_node(edg[1], label=edg[1],
               x = spk_coord[edg[1]][0], y = spk_coord[edg[1]][1],
            )

Where spk_coord is a dictionary that contains for each character of my network the x and y coordinates, like this:

        spk_coord = {
            "eddiewillows": [50,50],
            "jesseoverton": [50,100],
            "conradecklie": [50,150],
            "sheriff_brianmobley": [100,50],
            "tedgoggle": [100,100],
            "lie_detector_operator": [100,150],
            "nick": [150,50],
            "warrick": [150,100],
            "det_oriley": [150,150],
            "brass": [200,50],
            "tinacollins": [200,100],
            "sara": [200,150],
            "catherine": [300,50],
            "grissom": [300,100],
        }

I haven't managed yet to solve this and force the position of x and y to be applied. It looks mostly like the coordinates are not "really" applied, or I might be missing something in the implementation. Would you be able to help with this?

Thanks in advance!