Davide Fiocco
Davide Fiocco

Reputation: 5914

How can I color nodes of a graph, with datashader?

I want to visualize a graph with datashader (I have a lot of nodes), as in

import holoviews as hv
import pandas as pd
import dask.dataframe as dd
from holoviews.operation.datashader import (
    datashade, aggregate, dynspread,
    bundle_graph, split_dataframe, regrid
)
from holoviews.element.graphs import layout_nodes
from datashader.layout import random_layout

hv.extension('bokeh')

sources = [3, 1, 2, 3, 4]
targets = [5, 5, 5, 5, 5]
df = pd.DataFrame({'source': sources, 'target': targets})
edges_df = dd.from_pandas(df, npartitions=3)

graph = layout_nodes(hv.Graph(edges_df), layout=random_layout)
pad = dict(x=(-.5, 1.3), y=(-.5, 1.3))
datashade(graph, width=800, height=800) * graph.nodes.redim.range(**pad)

This works, but as my graph is bipartite, I would like to color the sources and targets nodes with different colors, e.g. using a color palette like:
my_colors_dict = {5: 'red', 3: 'blue', 1: 'blue', 2: 'blue', 4: 'blue'}
(i.e. all nodes blue but my single node "5" in my targets)

How can I achieve this? I am not very familiar with the library yet and could come up with clumsy attempts only so far..

Upvotes: 1

Views: 513

Answers (1)

James A. Bednar
James A. Bednar

Reputation: 3255

You should be able to do this by assigning a category to each node and then mapping that column to a color as described in http://holoviews.org/user_guide/Style_Mapping.html. But if you don't want to change your data structures and don't mind being a bit hackish, you can always do it by overlaying a recolored subset of the nodes:

targets = graph.nodes.clone()
targets.data = graph.nodes.data[4:]

datashade(graph, width=800, height=800) * graph.nodes.redim.range(**pad) * targets.opts(color='red')

enter image description here

Upvotes: 1

Related Questions