Make interactive network in D3 javascript.

d3graph.d3graph.adjmat2dict(adjmat: DataFrame, filter_weight: float = 0.0, scaler: str = 'zscore', marker_start=None, marker_end='arrow', marker_color='#808080', label=None, label_color='#808080', label_fontsize: int = 8, edge_weight: int = 1, edge_distance: int = 50, edge_style=0, minmax: list = [0.5, 15], minmax_distance: list = [50, 100], return_adjmat=True) dict

Convert adjacency matrix into vector with source and target.

Parameters:
  • adjmat (pd.DataFrame()) – Adjacency matrix.

  • filter_weight (float) – edges are returned with a minimum weight.

  • scaler (str, (default: 'zscore')) – Scale the edge-width using the following scaler: ‘zscore’ : Scale values to Z-scores. ‘minmax’ : The sklearn scaler will shrink the distribution between minmax. None : No scaler is used.

  • marker_start ((list of) str, (default: 'arrow')) – The start of the edge can be one of the following markers: ‘arrow’,’square’,’circle’,’stub’,None or ‘’

  • marker_end ((list of) str, (default: 'arrow')) – The end of the edge can be one of the following markers: ‘arrow’,’square’,’circle’,’stub’,None or ‘’

  • marker_color (str, (default: '#808080')) – The label color in hex.

  • label (str, (default: None)) – None : No label ‘weight’ : Weight of the edge list : The edge label.

  • label_color (str, (default: None)) – The label color in hex. None : Inherits the color from marker_color.

  • label_fontsize (int, (default: 8)) – The fontsize of the label.

  • edge_weight (Int (default: 10)) – Thickness of the edges. * None: Weighted approach using edge weights in the adjacency matrix. Weights are normalized between the minmax * 10: Constant edge distance

  • edge_distance (Int (default: 50)) – Distance between the edges. * None: Distance is based on the weights in the adjacency matrix. Weights are normalized between the minmax * 50: Constant edge distance

  • edge_style (float of str (default: 0)) – Style of the edges. * 0: straight line * 5: dashed line

  • minmax (tuple(int,int), (default: [0.5, 15])) – Thickness of the edges are normalized between minimum and maximum * [0.5, 15] * None: Do not change

  • minmax_distance (tuple(int,int), (default: [50, 100])) – Distances between the edges are normalized between minimum and maximum * [50, 100] * None: Do not change

Returns:

edge_properties

key: (source, target)

’weight’: weight of the edge. ‘weight_scaled’: scaled weight (thickness) of the edge. ‘edge_distance’: scaled distance of the edge. ‘edge_style’: style of the edge. ‘color’: color of the edge. ‘marker_start’: ‘’, ‘circle’, ‘square’, ‘arrow’, ‘stub’ ‘marker_end’: ‘’, ‘circle’, ‘square’, ‘arrow’, ‘stub’ ‘marker_color’: hex color of the marker. ‘label’: Text label for the edge. ‘label_color’: color of the label. ‘label_fontsize’: fontsize of the label.

Return type:

dict

d3graph.d3graph.adjmat2vec(adjmat, min_weight: float = 1.0) DataFrame

Convert adjacency matrix into vector with source and target.

Parameters:
  • adjmat (pd.DataFrame()) – Adjacency matrix.

  • min_weight (float) – edges are returned with a minimum weight.

Returns:

nodes that are connected based on source and target

Return type:

pd.DataFrame()

Examples

>>> source = ['Cloudy', 'Cloudy', 'Sprinkler', 'Rain']
>>> target = ['Sprinkler', 'Rain', 'Wet_Grass', 'Wet_Grass']
>>> adjmat = vec2adjmat(source, target, weight=[1, 2, 1, 3])
>>> vector = adjmat2vec(adjmat)
d3graph.d3graph.create_unique_dataframe(X, logger=None)

Combine source-target into adjacency matrix with updated weights.

Parameters:
  • X (DataFrame) – Data frame containing the columns [source, target, weight].

  • logger (Object, optional) – Logger object. The default is None.

Returns:

X – Unique adjacency matrix containing with index as source and columns as target labels. Weights are in the matrix.

Return type:

pd.DataFrame

References

  • This function is similar to that of d3blocks.

class d3graph.d3graph.d3graph(collision: float = 0.5, charge: int = 450, slider=None, support: str = 'text', verbose: int = 20)

Create interactive networks in d3js.

d3graph is a Python library that is built on d3js to create interactive and standalone networks. The input data is an adjacency matrix for which the columns and indexes are the nodes and elements>0 the edges. The output is an HTML file that is interactive and standalone.

Parameters:
  • collision (float, (default: 0.5)) – Response of the network. Higher means that more collisions are prevented.

  • charge (int, (default: 250)) – Edge length of the network. Towards zero becomes a dense network. Higher make edges longer.

  • slider (list [min: int, max: int]:, (default: [None, None])) – [None, None] : Slider is automatically set to the min-max range using the edge weights. [0, 10] : Slider is set to user defined range

  • verbose (int, (default: 20)) – Print progress to screen. 60: None, 40: Error, 30: Warn, 20: Info, 10: Debug

Return type:

None.

References

display(html)

Display.

get_cluster_color(node_names: list = None, color: str = '#000080') tuple

Clustering of graph labels.

Parameters:

df (Pandas DataFrame with columns) – ‘source’ ‘target’ ‘weight’

Return type:

dict group.

graph(adjmat, color: str = 'cluster', opacity: str = 'degree', size='degree', scaler: str = 'zscore', cmap: str = 'Set2') None

Process the adjacency matrix and set all properties to default.

This function processes the adjacency matrix. The nodes are the column and index names. A connect edge is seen in case vertices have values larger than 0. The strenght of the edge is based on the vertices values.

Parameters:
  • adjmat (pd.DataFrame()) – Adjacency matrix (symmetric). Values > 0 are edges.

  • color (list of strings (default: 'cluster')) – Coloring of the nodes. * ‘cluster’ or None : Colours are based on the community distance clusters.

  • size (array of integers (default: 5)) – Size of the nodes. * ‘degree’ size is based on the centrality measure. * 10: all nodes sizes are set to 10 * [10, 5, 3, 1, …]: Specify node sizes

  • opacity (list of floats (default: 'degree')) – Set the opacity of the node [0-1] where 0=transparant and 1=no transparancy. * None: Colors are inhereted from the initialization * ‘degree’ opacity is based on the centrality measure. * 0.99: All nodes will get this transparancy * [‘0.4, 0.1, 0.3,…] * [‘A’,’A’,’B’,…]: Opacity is generated using cmap and according to the unique labels.

  • scaler (str, (default: 'zscore')) – Scale the edge-width using the following scaler: ‘zscore’ : Scale values to Z-scores. ‘minmax’ : The sklearn scaler will shrink the distribution between minmax. None : No scaler is used.

Examples

>>> from d3graph import d3graph
>>>
>>> # Initialize
>>> d3 = d3graph()
>>>
>>> # Load karate example
>>> adjmat, df = d3.import_example('karate')
>>>
>>> # Initialize
>>> d3.graph(adjmat)
>>>
>>> # Node properties
>>> d3.set_node_properties(label=df['label'].values, color=df['label'].values, size=df['degree'].values, edge_size=df['degree'].values, cmap='Set1')
>>>
>>> # Edge properties
>>> d3.set_edge_properties(directed=True)
>>>
>>> # Plot
>>> d3.show()
Return type:

None

import_example(data='energy', url=None, sep=',')

Import example dataset from github source.

Import one of the few datasets from github source or specify your own download url link.

Parameters:
  • data (str) – Name of datasets: ‘sprinkler’, ‘titanic’, ‘student’, ‘fifa’, ‘cancer’, ‘waterpump’, ‘retail’

  • url (str) – url link to to dataset.

Returns:

Dataset containing mixed features.

Return type:

pd.DataFrame()

References

open_browser(sleep: float = 0.5) None

Open the browser to show the chart.

set_edge_properties(edge_distance=None, edge_weight=None, edge_style=0, scaler: str = 'zscore', directed: bool = False, marker_start=None, marker_end='arrow', marker_color='#808080', label: str = None, label_color='#808080', label_fontsize: int = 8, minmax=[0.5, 15], minmax_distance=[50, 100]) dict

Edge properties.

Parameters:
  • edge_distance (Int (default: 50)) – Distance between the edges. * None: Distance is based on the weights in the adjacency matrix. Weights are normalized between the minmax * 50: Constant edge distance

  • edge_weight (Int (default: None)) – Thickness of the edges. * None: Weighted approach using edge weights in the adjacency matrix. Weights are normalized between the minmax * 10: Constant edge distance

  • edge_style (float of str (default: 0)) – Style of the edges. * 0: straight line * 5: dashed line

  • scaler (str, (default: 'zscore')) – Scale the edge-width using the following scaler: ‘zscore’ : Scale values to Z-scores. ‘minmax’ : The sklearn scaler will shrink the distribution between minmax. None : No scaler is used.

  • directed (Bool, (default: False)) – True: Edges are shown with an marker (e.g. arrow) False: Edges do not show markers.

  • marker_start ((list of) str, (default: 'arrow')) – The start of the edge can be one of the following markers: ‘arrow’,’square’,’circle’,’stub’,None or ‘’

  • marker_end ((list of) str, (default: 'arrow')) – The end of the edge can be one of the following markers: ‘arrow’,’square’,’circle’,’stub’,None or ‘’

  • marker_color (str, (default: '#808080')) – The label color in hex.

  • label (str, (default: '')) – None : No labels ‘weight’ : This will add the weights on each edge. list : The edge label.

  • label_color (str, (default: None)) – The label color in hex. None : Inherits the color from marker_color.

  • label_fontsize (int, (default: 8)) – The fontsize of the label.

  • minmax (tuple(float, float), (default: [0.5, 15.0])) – Edge thickness is normalized between minimum and maximum * [0.5, 15] * None: Do not change

  • minmax_distance (tuple(float, float), (default: [50, 100])) – Distances are normalized between minimum and maximum * [50, 100] * None: Do not change

Returns:

edge_properties

key: (source, target)

’weight’: weight of the edge ‘weight_scaled’: scaled weight of the edge ‘color’: color of the edge

Return type:

dict

set_node_properties(label=None, marker='circle', tooltip=None, color='cluster', opacity='degree', size='degree', edge_color='#000000', edge_size=1, fontcolor='node_color', fontsize=12, cmap: str = 'Set2', scaler: str = 'zscore', minmax=[8, 13])

Node properties.

Parameters:
  • label (list of labels (default: None)) – The text that is shown on the Node. If not specified, the label text will be inherited from the adjacency matrix column-names. * [‘label 1’,’label 2’,’label 3’, …]

  • marker (list of markers (default: 'circle')) – The marker that is used for the Node. * [‘circle’,’rect’,’rect’, …]

  • tooltip (list of names (default: None)) – The text that is shown when hovering over the Node. If not specified, the text will inherit from the label. * [‘tooltip 1’,’tooltip 2’,’tooltip 3’, …]

  • color (list of strings (default: cluster')) – Color of the node. * None: Colors are inhereted from the initialization * ‘cluster’: Colours are based on the community distance clusters. * ‘#000000’: All nodes will get this hex color. * [‘#377eb8’,’#ffffff’,’#000000’,…]: Hex colors are directly used. * [‘A’]: All nodes will have the same color. Color is generated on CMAP and the unique labels. * [‘A’,’A’,’B’,…]: Colors are generated using cmap and according to the unique labels.

  • opacity (list of floats (default: 'degree')) – Set the opacity of the node [0-1] where 0=transparant and 1=no transparancy. * None: Colors are inhereted from the initialization * ‘degree’ opacity is based on the centrality measure. * 0.99: All nodes will get this transparancy * [‘0.4, 0.1, 0.3,…] * [‘A’,’A’,’B’,…]: Opacity is generated using cmap and according to the unique labels.

  • size (array of integers (default: 5)) – Size of the nodes. * ‘degree’ opacity is based on the centrality measure. * 10: all nodes sizes are set to 10 * [10, 5, 3, 1, …]: Specify node sizes

  • fontcolor (list of strings (default: node_color')) – Color of the node. * ‘node_color’ : Colours are inherited from the node color * ‘cluster’ : Colours are based on the community distance clusters. * ‘#000000’: All nodes will get this hex color. * [‘#377eb8’,’#ffffff’,’#000000’,…]: Hex colors are directly used. * [‘A’]: All nodes will have the same color. Color is generated on CMAP and the unique labels. * [‘A’,’A’,’B’,…]: Colors are generated using cmap and the unique labels accordingly colored.

  • fontsize (array of integers (default: 10)) – Size of the node text.. * 10: All nodes will be set on this size, * [10, 20, 5,…] Specify per node the text size.

  • edge_color (list of strings (default: '#000080')) – Edge color of the node. * ‘cluster’ : Colours are based on the community distance clusters. * [‘#377eb8’,’#ffffff’,’#000000’,…]: Hex colors are directly used. * [‘A’]: All nodes will have the same color. Color is generated on CMAP and the unique labels. * [‘A’,’A’,’B’,…]: Colors are generated using cmap and the unique labels recordingly colored.

  • edge_size (array of integers (default: 1)) – Size of the node edge. Note that node edge sizes are automatically scaled between [0.1 - 4]. * 1: All nodes will be set on this size, * [2,5,1,…] Specify per node the edge size.

  • cmap (String, (default: 'Set1')) – All colors can be reversed with ‘_r’, e.g. ‘binary’ to ‘binary_r’ ‘Set1’, ‘Set2’, ‘rainbow’, ‘bwr’, ‘binary’, ‘seismic’, ‘Blues’, ‘Reds’, ‘Pastel1’, ‘Paired’

  • scaler (str, (default: 'zscore')) – Scale the edge-width using the following scaler: ‘zscore’ : Scale values to Z-scores. ‘minmax’ : The sklearn scaler will shrink the distribution between minmax. None : No scaler is used.

  • minmax (tuple, (default: [0.5, 15])) – Scale the node size in the range of a minimum and maximum [5, 50] using the following scaler: ‘zscore’ : Scale values to Z-scores. ‘minmax’ : The sklearn scaler will shrink the distribution. None : No scaler is used.

Returns:

node_properties

key: node_name

’label’: Label of the node ‘marker’: marker of the node ‘color’: color of the node ‘opacity’: Opacity of the node ‘size’: size of the node ‘fontcolor’: color of the node text ‘fontsize’: node text size ‘edge_size’: edge_size of the node ‘edge_color’: edge_color of the node

Return type:

dict

set_path(filepath='d3graph.html') str

Set the file path.

Parameters:

filepath (str) – filename and or full pathname. * ‘d3graph.html’ * ‘c://temp/’ * ‘c://temp/d3graph.html’

Returns:

filepath – Path to graph.

Return type:

str

setup_slider() None

Minimum maximum range of the slider.

Returns:

tuple

Return type:

[min, max].

show(figsize=[1500, 800], title: str = 'd3graph', filepath: str = 'd3graph.html', showfig: bool = True, overwrite: bool = True, show_slider: bool = True, set_slider: bool = 0, click={'fill': None, 'size': 1.3, 'stroke': 'black', 'stroke-width': 3}, notebook: bool = False) None

Build and show the graph.

Parameters:
  • figsize (tuple, (default: (1500, 800))) – Size of the figure in the browser, (width, height). (None, None): Use the screen resolution.

  • title (String, (default: None)) – Title of the figure.

  • filepath (String, (Default: user temp directory)) – File path to save the output

  • showfig (bool, (default: True)) – Open the window to show the network.

  • overwrite (bool, (default: True)) – Overwrite the existing html file.

  • show_slider (bool, (default: True)) – True: Slider is shown in the HTML. False: Slider is not shown in the HTML.

  • set_slider (int, (default: 0)) – 0: Set the the slider with all edges connected 1,2,3, etc: Set slider at a threshold with that particular network state.

  • click (dict,) –

    On node click event. The size depicts the multiplication factor.
    • {‘fill’: ‘red’, ‘stroke’: ‘black’, ‘size’: 1.3, ‘stroke-width’: 3}

    • {‘fill’: None, ‘stroke’: ‘#FFF000’, ‘size’: 2, ‘stroke-width’: 1}

    • None : No action on click.

  • notebook (bool) – True: Use IPython to show chart in notebooks. False: Do not use IPython.

Return type:

html.

write_html(json_data, overwrite: bool = True) None

Write html.

Parameters:

json_data (json file) –

Return type:

None.

d3graph.d3graph.data_checks(adjmat: DataFrame) DataFrame

Check input Adjacency matrix.

Parameters:

adjmat (pd.DataFrame()) – Adjacency matrix (symmetric). Values > 0 are edges.

Returns:

adjmat

Return type:

pd.DataFrame()

d3graph.d3graph.edges2G(edge_properties: dict, G: Graph = None) Graph

Convert edges to Graph.

Parameters:
  • edge_properties (dictionary) – Dictionary containing edge properties

  • G (Networkx object) – Graph G.

Return type:

Graph G

d3graph.d3graph.get_support(support)

Support.

d3graph.d3graph.json_create(G: Graph) str

Create json from Graph.

Parameters:

G (Networkx object) – Graph G

Return type:

json dumps

d3graph.d3graph.library_compatibility_checks() None

Library compatibility checks.

Return type:

None.

d3graph.d3graph.make_graph(node_properties: dict, edge_properties: dict) dict

Make graph from node and edge properties.

Parameters:
  • node_properties (dictionary) – Dictionary containing node properties

  • edge_properties (dictionary) – Dictionary containing edge properties

Return type:

dict containing Graph G and dataframe.

d3graph.d3graph.nodes2G(node_properties: dict, G: Graph = None) Graph

Convert nodes to Graph.

Parameters:
  • node_properties (dictionary) – Dictionary containing node properties

  • G (Networkx object) – Graph G.

Return type:

Graph G

d3graph.d3graph.remove_special_chars(adjmat)

Remove special characters.

Parameters:

adjmat (pd.DataFrame()) – Adjacency matrix (symmetric). Values > 0 are edges.

Returns:

adjmat

Return type:

pd.DataFrame()

d3graph.d3graph.set_logger(verbose: int = 20) None

Set the logger for verbosity messages.

d3graph.d3graph.vec2adjmat(source, target, weight=None, symmetric: bool = True, aggfunc='sum') DataFrame

Convert source and target into adjacency matrix.

Parameters:
  • source (list) – The source node.

  • target (list) – The target node.

  • weight (list of int) – The Weights between the source-target values

  • symmetric (bool, optional) – Make the adjacency matrix symmetric with the same number of rows as columns. The default is True.

  • aggfunc (str, optional) – Aggregate function in case multiple values exists for the same relationship. ‘sum’ (default)

Returns:

adjacency matrix.

Return type:

pd.DataFrame

Examples

>>> source = ['Cloudy', 'Cloudy', 'Sprinkler', 'Rain']
>>> target = ['Sprinkler', 'Rain', 'Wet_Grass', 'Wet_Grass']
>>> vec2adjmat(source, target)
>>> weight = [1, 2, 1, 3]
>>> vec2adjmat(source, target, weight=weight)