Code Monkey home page Code Monkey logo

pyvis's Introduction

Pyvis - a Python library for visualizing networks

Description

Pyvis is built around visjs, a JavaScript visualization library.

Documentation

Pyvis' full documentation can be found at http://pyvis.readthedocs.io/en/latest/

Installation

You can install pyvis through pip:

pip install pyvis

Or if you have an archive of the project simply run the following from the top level directory:

python setup.py install

Dependencies

networkx

jinja2

ipython

jsonpickle

Test Dependencies

selenium

numpy

Quick Start

The most basic use case of a pyvis instance is to create a Network object and invoke methods:

from pyvis.network import Network

g = Network()
g.add_node(0)
g.add_node(1)
g.add_edge(0, 1)
g.show("basic.html")

Interactive Notebook playground with examples

Binder

pyvis's People

Contributors

aalok-sathe avatar amarvin avatar artemk1337 avatar berserkergaruk avatar bistaumanga avatar boludo00 avatar darkproduct avatar erictapen avatar glen-kurtz avatar henningtimm avatar inaokay-faber avatar ingokl avatar jbednar avatar jhunpingco avatar js-konda avatar khuyentran1401 avatar nanoseb avatar nocluebutalotofit avatar olive004 avatar pbayerle avatar pierre-vf avatar summerswallow-whi avatar sviperm avatar szobov avatar wilsonhchung avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyvis's Issues

drawing wrong arrow directions

Dear developers, thank you for this great library.

Unfortunately, it seems there are some issues with directed graphs, here is the first one.

When drawing directed graphs the arrows are plotted in the wrong direction:

screenshot 2018-12-06 at 10 12 39 2

Is there a way to pass initial options and allow buttons to manipulate them later?

Currently I am getting an error if I try to use the .set_options with my "preset" and use the .show_buttons afterwards. Would be pretty nice to disable physics if network graph ist positioned to enhance performance. Thanks!

/opt/conda/lib/python3.7/site-packages/pyvis/network.py in show_buttons(self, filter_)
844 """
845 self.conf = True
--> 846 self.options.configure = Configure(enabled=True, filter_=filter_)
847 self.widget = True
848

AttributeError: 'dict' object has no attribute 'configure'

Make link in label clickable

It would be nice if there was some way to keep a node's label displayed in such a way that linked elements within it could be clicked.

Centering Nodes

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

Alternative HTML Template

Hi developer team, can you allow users to specify their own HTML templates in visualization in future releases?

Network.from_nx doesn't inherit all properties

It seems like Network.from_nx doesn't inherit all properties of the graph, only the nodes and edges. Any color, and other properties have to be re-created/added to the Network representation of the networkx graph.

Add ability to customize physics layouts

Currently the barnes_hut, repulsion., hrepulsion, and force_atlas_2_based methods are called and set with default properties. When experimenting with visualizing different graphs, each of these properties should be able to be tweaked as needed to obtain the most efficient graph.

is there a way to visualize the network while it is getting constructed?

is there a way to visualize the network while it is getting constructed?

I understand this library is very good at providing an easy way to visualize static networks. But in my case I have a stream of edge coming in from a socket connection and I want to visualize them as soon as I receive and edge from the socket connection. How can I do that using library?

if not, any suggestion on a library that can do this in the most simplistic way like pyvis does for static graphs instead of exposing all the low level details?

Multiple edges between nodes?

Hi,

Seems like pyvis does not support MultiDiGraphs from networkx, does it?
When I add mutliple edges from A to B it always only retains the first one. Is that expected behaviour?
Any way to do that, any plans to support it?
I really love pyvis since its so easy to use, however, having multiple edges (and visualise them) is pretty important I feel.

Many thanks,
Jonathan

Version: '0.1.7.0'

Example:
g = net.Network()
g.add_node(1)
g.add_node(2)
g.add_edge(1, 2,data={1})
g.add_edge(1, 2,data={2})
g.get_edges()
Out[40]: [{'data': {1}, 'from': 1, 'to': 2}]

edge labels

Hi, is it possible to display edge labels/attributes with pyvis? Thanks.

requirement conflict in setup.py and requirements.txt

in setup.py the dependency for ipython is ==5.3.0 but in requirements.txt it's written >=5.3.0
therefore installation of pyvis using pip will downgrade back the existing ipython to 5.3.0. please fix and update python wheel file

Tweak/add additional custom templates

The current default HTML outputs contain a basic SVG canvas with dragging interactivity. It would be interesting to see how the HTML template can be tweaked to include custom JS to add additional interactivity or visual options.

usage of Network.set_options()

I'm trying to provide the options string generated by the dynamic network configuration tool to my network object before calling show() on it again, but I get an error every time.

import networkx as nx
from pyvis.network import Network

G = nx.star_graph(20)
nodes = G.nodes.data()
edges = G.edges.data()

g = Network(notebook=True)

{g.add_node(node[0]) for node in nodes}
{g.add_edge(edge[0], edge[1]) for edge in edges}

g.set_options('var options = {  "nodes": {    "color": {      "hover": {        "border": "rgba(231,44,233,1)"      }    },    "shape": "dot"  },  "edges": {    "arrowStrikethrough": false,    "color": {      "highlight": "rgba(132,48,51,1)",      "hover": "rgba(128,25,132,1)",      "inherit": false    },    "smooth": {      "type": "vertical",      "forceDirection": "none"    }  },  "physics": {    "barnesHut": {      "gravitationalConstant": -80000,      "springLength": 250,      "springConstant": 0.001    },    "minVelocity": 0.75  }}')

g.show("ex.html")

This code returns the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-ae5445ab43fb> in <module>()
      4 {g.add_edge(edge[0], edge[1]) for edge in edges}
      5 g.show_buttons()
----> 6 g.set_options('var options = {  "nodes": {    "color": {      "hover": {        "border": "rgba(231,44,233,1)"      }    },    "shape": "dot"  },  "edges": {    "arrowStrikethrough": false,    "color": {      "highlight": "rgba(132,48,51,1)",      "hover": "rgba(128,25,132,1)",      "inherit": false    },    "smooth": {      "type": "vertical",      "forceDirection": "none"    }  },  "physics": {    "barnesHut": {      "gravitationalConstant": -80000,      "springLength": 250,      "springConstant": 0.001    },    "minVelocity": 0.75  }}')
      7 g.show("ex.html")

AttributeError: 'Network' object has no attribute 'set_options'

Am I using set_options() incorrectly? I tried to bypass it by calling g.options.set(), but that gave the same error. I see the function definitions in the code, so I don't understand why they're not being found.
I also noticed that in the readthedocs.io page for network.py doesn't have an entry for set_options. Perhaps unrelated.

show_buttons in notebook

Thanks for a super useful module! Is it possible to use show_buttons in a Jupyter notebook? I tried calling g.show_buttons() before and after g.show() and it didn't seem to have any effect?

Loading Bar Stuck on 0% when Background has rendered

If your node graph is very large the loading bar will remain visible (at 0%) even though the graph has loaded in the background. If you customise the graph with the menu you can see the graph changing in the background and ultimately you have to push F12 in the browser and delete the HTML element for the loading bar to see the final result.

google colab

Hi, great package! I was wondering if you had any tips for getting the graph to load in google colab. Currently, I get 'localhost refused to connect' as an error.

Onclick event on button

May I know if there is a way to click on a button and have something like an onclick event?

unable to draw bidirectional dependencies

I would like to plot this, which is a very common pattern in my networks:

bidirectional png 001

Unfortunately, it doesn't seem to work:

screenshot 2018-12-06 at 10 13 32 2

Is this a bug or a limitation of the network structure?

Recommend any html viewer?

would you please like to recommend me any html viewer that can visualize heavy graph. btw thanks for such a great library

disproportional edge thickness

When drawing edges with different values, I would expect the thickness to be proportional to the values. For instance, in this case where the values are 10 and 12, I would expect one arrow to be 20% larger than the other:

screenshot 2018-12-06 at 11 15 07 2

This can be fixed by creating an hidden edge with a value of 0:

screenshot 2018-12-06 at 11 15 39 2

But it would be nice to see the expected sizes without using this workaround.

Network.from_nx doesnt import isolated nodes if edges exist

When edges exist the only nodes that are created are ones that are part of edges. Any nodes not part of an edge dont get imported. nx.isolates(G) will return an iterable that has all the nodes that are not part of edges. Looping over this would allow for adding these nodes after adding the nodes from the edges.

Using title in node and edge

This is regarding using title for both node and edge.
When using HTML a tag and href for a local pdf as title in add_node() in Pyvis, it works and allow me to down load and show the pdf in a separate tab, but the separate title that was specified in add_edge is no longer shown when the mouse move over the edge. Using iframe instead of a tag for node works and edge title was shown when the mouse move over it, but the pdf iframe disappear as soon as the mouse move and its hard to use the pdf in the iframe, I prefer to view the pdf, enlarge it and able to moving the mouse around. The generation of the node title html is as follow :

def create_pdf_download (pdf_title,pdf_link):

prefix = "<a target="_tab" href="
postfix = ">"+ pdf_title + ""
return prefix + pdf_link + postfix

I notice that the html code generated for G.html at the edge is a bit different in the two scenarios but I have very little html know-how

Thanks

Network visualisation fails after disabling physics for node or edge.

After disabling physics for a specific node (by setting argument physics in method Network.add_node() to False) network rendering fails - only background is visible.

Same thing when disabling physics for an edge.

Minimal working example, following tutorial from readme:

from pyvis.network import Network
g = Network()
g.add_node(0, physics=False)
g.add_node(1)
g.add_edge(0,1)
g.show("basic.html")

P.S. I love this package!

Filtering nodes

Is there a way to select a node and visualize only the nodes that are connected with the selected one ?

Example notebook

It would be useful to add an example notebook that could be run in MyBinder for example.

Example notebook based on docs attached.

The repo also runs straightforwardly in MyBinder: adding a MyBinder button to the README would simplify access to this: Binder

Example.ipynb.zip

Allow setting options as dictionary

With using .show_buttons() it is possible to test all configuration directly in browser and then copy the settings as a json, but it is not possible to use it as a input in python.

My dirty solution works like this ->

  1. changed this line in source code
def get_network_data(self):
       return (self.nodes, self.edges, self.height,
               self.width, json.dumps(self.options))
  1. Copied JSON from the UI after setting desirable options (manually set all true and false options to python True and False)

options = {
"nodes": {
"shape": "dot",
"size": 10
},
"edges": {
"color": {
"inherit": True
},
"smooth": False
},
"layout": {
"hierarchical": {
"enabled": True,
"direction": "LR",
"sortMethod": "directed"
}
},
"interaction": {
"navigationButtons": True
},
"physics": {
"hierarchicalRepulsion": {
"centralGravity": 0,
"springLength": 75,
"nodeDistance": 145,
"damping": 0.2
},
"maxVelocity": 28,
"minVelocity": 0.75,
"solver": "hierarchicalRepulsion"
}
}

  1. Result

graph.options = options

graph.show(r"test.html")

image

Various Behaviors of Edges

Hi developers team, I am using pyvis for a network analysis. Consider I have node A to node B in a directed graph. On the HTML page, when I drag node A I want node B following node A, so I turn on the physics status and initialize the energy function of spring. When I drag node B later, I do not want node A follwoing node B or bouncing because of the spring, can I achieve this without turning off all phycis option of the network?
Sincerely
Eik

pyvis- Distance between nodes

Is it possible to specify the distance between nodes (that means the length of the edges)?
It is indeed possible to define the width but not the length.
Two "similar" nodes could be represented very close in the space ...

Thanks!

How to implement the same layout for many graphs?

Hi,

I was wondering what is the right way of implementing the same layout for many graphs. I would like to physics engine disabled (physics=False) and then set the x,y based on a scheme.

Do you have something like that? Maybe an example? How is x,y work? Does it start from the upper left corner? Thanks in advance.

to_json error

Hello

Getting an error when calling the to_json method.

~/anaconda3/envs/default/lib/python3.6/site-packages/pyvis/network.py in (o)
767
768 def to_json(self):
--> 769 return json.dumps(self, default=lambda o: o.dict,
770 sort_keys=True, indent=4)
771

AttributeError: 'builtin_function_or_method' object has no attribute 'dict'

Any suggestions?

setting edge color?

Hi, I am trying to find a way to set edge color without luck. Can anyone help me, or let me know if it is going to be implemented in near future?

I tried show_buttons function, it gave me a toggle to set colors but didn't seem to be effective.
image

Thanks.

"fixed" option?

I'm trying to set positions manually by giving x, y and sett physics=False but can't get it to work.
The documentation mentions a "fixed" option:

node to that position use the physics or fixed options.

But I can't seem to find any other mention of it when grep'ing the source...

Parameterize 'mynetwork' value in order to uniquely identify container for rendered graphs

Currently the container element for graphs in template.html has the static id 'mynetwork'. This is causing problems when attempting to use pyvis for rendering multiple graphs in iFrames within a single Jupyter notebook, as all rendering past the first call loads into the initially generated 'mynetwork' div, associated with the first rendered pyvis graph in the notebook, as opposed to the div generated by the call. The bandaid solution to this is to generate random IDs for the container for each call, e.g.:

Graph.html = finalHTML.replace('#mynetwork','#{}'.format(randID)).replace('<div id = "mynetwork"','<div id = "{}"'.format(randID)).replace("docu\
ment.getElementById('mynetwork')","document.getElementById('{}')".format(randID))

However it would be safer to parameterize the value 'mynetwork' by a placeholder along the lines of {{width}} and {{height}}`.

Creating "group" for nodes

Vis.js gives to option to create groups to apply layout and style options. How would I do this with pyvis? Could you please give a simple example.

Using hrefs in title

Hey, there is a problem when using hrefs in the title of a node and wanting to add a title to an edge. i looked at the code and what's happening is basically that

.vis-network-tooltip {
display:none;
}

just hides everything. but i guess if you change it then there will be two titles on the nodes.. would be nice if you could fix it

all the best

Pyvis only supports string and int types

Summary

It would be much better if pyvis supported any hashable types like networkx. This would enable the from_nx interface to be much more flexible. Would it be an option to simply convert the items to a string for rendering if required, but allow a network with any hashable type as a node?

Related entities

#16

3D visualization

Hi All,
I would like to know if it is possible to visualize 3D networks.

None showed when heading is not provided

image

As shown in the image, the rendered HTML shows None for heading. This is caused by PR #67. The logic of HTML rendering template should not display the h2 tag if the heading is None.

@WilsonHChung would you mind looking into that? I like the heading features a lot BTW.

Empty AssertionError when using np.array

When trying to create a network graph from Jupyter with np.array as input, an exception is thrown

arrayNodes = np.array([1,2,3,4])
g = Network(notebook=True)
g.add_nodes(np.array([1,2,3,4]))

throws


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-91-b8c17924b890> in <module>()
      1 arrayNodes = np.array([1,2,3,4])
      2 g = Network(notebook=True)
----> 3 g.add_nodes(np.array([1,2,3,4]))

C:\anaconda\lib\site-packages\pyvis\network.py in add_nodes(self, nodes, **kwargs)
    247 
    248         for node in nodes:
--> 249             assert isinstance(node, int) or isinstance(node, str)
    250             self.add_node(node, **nd[node])
    251 

AssertionError: 

isinstance check too strict

Hi, thank you for making this project available--it looks really interesting.
I'm just getting started and immediately ran into this (when using from_nx):

> /usr/local/lib/python3.6/dist-packages/pyvis/network.py(197)add_node()
    195         :type y: num (optional)
    196         """
--> 197         assert isinstance(n_id, str) or isinstance(n_id, int)
    198         if label:
    199             node_label = label

ipdb> p n_id
2
ipdb> p type(n_id)
<class 'numpy.int64'>

one possible fix would be to check against the abstract base class:

ipdb> from numbers import Integral
ipdb> isinstance(n_id, Integral)
True

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.