Soerendip
Soerendip

Reputation: 9185

How to hide node labels in pyvis network?

I have a network with around 100 nodes which are highly connected. Now, the all the labels look very messy. I tried to remove the label setting the label attribute to None or '', but then the id's are shown instead. Is there a way to hide the labels or only show the labels of selected nodes and edges?

Upvotes: 3

Views: 4416

Answers (2)

tabeare
tabeare

Reputation: 21

You can hide the labels by setting a transparent font color. For example like this:

from pyvis.network import Network

net = Network(font_color='#10000000')
net.from_nx(G)
net.show('example.html')

This makes all the node labels disappear in my case (Technically they are still there, but they are not visible anymore).

Upvotes: 1

PatS
PatS

Reputation: 21

From the docs (https://pyvis.readthedocs.io/en/latest/_modules/pyvis/network.html) I see that the add_node method of the Network class contains the logical test if label. This will evaluate to False if label is None or an empty string (""), but will evaluate to True if you use try to approximate an empty string with nothing but a space " ".

Failing the above, you could try editing the code in add_node, or (perhaps preferably) defining your own Network that inherits from the original and over-writes the add_node method. Maybe something like this:

from pyvis.network import Network

class AbsoluteLabelNetwork(Network):
    """A version of the pyvis.network.Network class that always uses the label provided"""
    def add_node(self, n_id, label=None, shape="dot", **options):
        """See parent class for docstr, with the exception that label will always be used"""
        assert isinstance(n_id, str) or isinstance(n_id, int)
        node_label = label  # note: change from package version
        if n_id not in self.node_ids:
            n = Node(n_id, shape, label=node_label, font_color=self.font_color, **options)
            self.nodes.append(n.options)
            self.node_ids.append(n_id)

Please note that these possible solutions are untested so I'd be interested if they helped you.

Upvotes: 2

Related Questions