D3graph
Note
This page contains a summary of the possiblities what you can do with D3graph. More details can be found on the D3graph documentation pages.
- D3Blocks.d3graph(df, color='cluster', size='degree', opacity='degree', scaler='zscore', directed=False, marker_start=None, marker_end='arrow', marker_color='#808080', title='D3graph - D3blocks', filepath='d3graph.html', cmap='Set2', figsize=[None, None], collision=0.5, charge=600, link_tension: float = 1, slider=[None, None], set_slider=0, show_slider=True, click={'fill': None, 'size': 1.3, 'stroke': 'black', 'stroke-width': 3}, color_background=None, show_top_panel: bool = True, show_side_panel: bool = True, dark_mode=True, sticky: bool = None, node_text_inside: bool = False, max_ticks: int = 300, label_zoom_threshold: float = 0.4, canvas_edge_threshold: int = 2000, show_density: bool = False, density_grid_size: int = 60, density_blur: int = 15, density_opacity: float = 0.8, highlight_full_network: bool = True, support='text', notebook=False, showfig=True, overwrite=True, return_html: bool = False)
d3graph block.
d3graph is integrated in d3blocks and is to create interactive and stand-alone D3 force-directed graphs. The input data is a dataframe containing source, target, and weight. In underneath example, we load the energy dataset which contains 68 relationships that are stored in a DataFrame with the columns source, target, and weight. The nodes are colored based on the Louvain heuristics which is the partition of highest modularity, i.e. the highest partition of the dendrogram generated by the Louvain algorithm. The strength of the edges is based on the weights. To explore the network, and the strength of the edges more extensively, the slider (located at the top) can break the network based on the edge weights. The ouput is a html file that is interactive and stand alone. For demonstration purposes, the “energy” and “stormofswords” dataset can be used.
- Parameters:
df (pd.DataFrame()) –
- Input data containing the following columns:
’source’
’target’
’weight’
color (list of strings (default: '#000080')) –
- Color of the node.
’cluster’ : Colours are based on the community distance clusters.
None: All nodes will have the same color (auto generated).
[‘#000000’]: All nodes will have the same hex color.
[‘#377eb8’,’#ffffff’,’#000000’,…]: Hex colors are directly used.
[‘A’]: All nodes will have hte 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.
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
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.
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.
collision (float, (default: 0.5)) – Response of the network. Higher means that more collisions are prevented.
charge (int, (default: 400)) – Edge length of the network. Towards zero becomes a dense network. Higher make edges longer.
cmap (String, (default: 'Set1')) –
- All colors can be reversed with ‘_r’, e.g. ‘binary’ to ‘binary_r’
’tab20c’, ‘Set1’, ‘Set2’, ‘rainbow’, ‘bwr’, ‘binary’, ‘seismic’, ‘Blues’, ‘Reds’, ‘Pastel1’, ‘Paired’, ‘twilight’, ‘hsv’, ‘inferno’
slider (typle [min: int, max: int]:, (default: [None, None])) – Slider is automatically set to the range of the edge weights.
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.
show_slider (bool, (default: True)) – True: Slider is shown in the HTML. False: Slider is not shown in the HTML.
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.
color_background (list or str, optional) – Background for page, top panel, and side panels.
[dark_hex, light_hex], or a named preset (e.g.'streamlit'). None uses theme defaults.dark_mode (bool, optional) – If True, enables dark mode for the visualization. Default is False.
title (String, (default: None)) –
- Title of the figure.
’d3graph’
filepath (String, (Default: user temp directory)) –
- File path to save the output.
Temporarily path: ‘d3blocks.html’
Relative path: ‘./d3blocks.html’
Absolute path: ‘c://temp//d3blocks.html’
None: Return HTML
figsize (tuple) –
- Size of the figure in the browser, [width, height].
[1500, 800]
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
sticky (bool, (default: None)) – When True, nodes stay fixed in place after being dragged (overrides the value set in __init__). When False, nodes are released after dragging (default simulation behaviour). When None, the value set in __init__ is used. Right-click a fixed node to release it back into the simulation.
max_ticks (int, (default: 300)) – Caps how many simulation ticks run before the force layout auto-stops, instead of letting it cool down naturally (which can take thousands of ticks on large graphs, each re-running collision detection over every node). 0 or None: disable the cap and run to natural cooldown.
label_zoom_threshold (float, (default: 0.6)) – Node and edge labels are hidden below this zoom scale (unreadable anyway, and costly to keep rendering for large graphs) and reappear once zoomed back in past it. Uses a single CSS class toggle, not per-label work. 0: never hide.
canvas_edge_threshold (int, (default: 2000)) – Above this many visible edges, edges are drawn on a <canvas> layer instead of as individual SVG <line> elements. SVG’s per-element DOM overhead is what makes tens of thousands of edges freeze the page; canvas draw calls stay cheap regardless of edge count.
show_density (bool, (default: False)) – Adds a node-clustering heatmap layer (grid-binned density of node positions).
density_grid_size (int, (default: 40)) – Grid resolution for the density heatmap (cells along the longer axis of the node bounding box). Higher = finer detail on tight clusters, more cells to draw.
density_blur (int, (default: 8)) – Blur radius (px) applied to the heatmap for a smooth look instead of a blocky grid.
density_opacity (float, (default: 0.6)) – Maximum heatmap opacity, reached at the highest-density grid cell.
highlight_full_network (bool, (default: True)) – Controls how much of the graph lights up when a node is clicked. True: The entire connected network reachable from the clicked node is highlighted; everything outside that component is dimmed. False: Only the clicked node’s directly-connected neighbors/edges (one hop) are highlighted, matching the old default behavior.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
show_side_panel (bool, (default: True)) – Render the side panels (Export, Network Statistic, Physics, etc.). Set to False when embedding the generated HTML into an existing page/app that provides its own UI chrome (streamlit).
show_top_panel (bool, (default: True)) – Render the top chrome (logo, search field, and the Dark Mode / Hide Edges / Show Density buttons).
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
return_html (bool, (default: False)) –
True: Return the generated HTML string (useful for Streamlit, notebooks, embedding).
False: Do not return HTML.
- Return type:
None.
Examples
>>> # Load library >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Import example >>> df = d3.import_example('energy') # 'bigbang', 'stormofswords' >>> # >>> # Create network using default >>> d3.d3graph(df, filepath='d3graph.html') >>> # >>> # Change scaler >>> d3.d3graph(df, scaler='minmax') >>> # >>> # Change node properties >>> d3.D3graph.set_node_properties(color=None) >>> d3.D3graph.node_properties['Solar']['size']=30 >>> d3.D3graph.node_properties['Solar']['color']='#FF0000' >>> d3.D3graph.node_properties['Solar']['edge_color']='#000000' >>> d3.D3graph.node_properties['Solar']['edge_size']=5 >>> d3.D3graph.show() >>> # >>> # Change edge properties >>> d3.D3graph.set_edge_properties(directed=True, marker_end='arrow') >>> d3.D3graph.show() >>> # >>> # Node properties >>> d3.D3graph.node_properties >>> # >>> # Node properties >>> d3.D3graph.edge_properties >>> # >>> # After making changes, show the graph again using show() >>> d3.D3graph.show()
References
Github : https://github.com/erdogant/d3graph
Documentation: https://erdogant.github.io/d3graph/
Blog
Input Data
The input dataset is a DataFrame with three column, source, target and weight.
# source target weight
# 0 Agricultural 'waste' Bio-conversion 124.729
# 1 Bio-conversion Liquid 0.597
# 2 Bio-conversion Losses 26.862
# 3 Bio-conversion Solid 280.322
# 4 Bio-conversion Gas 81.144
# .. ... ... ...
# 63 Thermal generation District heating 79.329
# 64 Tidal Electricity grid 9.452
# 65 UK land based bioenergy Bio-conversion 182.010
# 66 Wave Electricity grid 19.013
# 67 Wind Electricity grid 289.366
# [68 rows x 3 columns]
Social Media Example
Interactive example:
View the social media network visualization