API References
d3blocks library.
- class d3blocks.d3blocks.D3Blocks(chart: str = None, frame: bool = True, verbose: int = 20, support: str = 'text')
D3Blocks.
- Parameters:
frame (Bool, (default: True)) – True: Return in DataFrame. False: Return in dictionary.
verbose (int, optional) – Verbose message. The default is 20.
support (String, (default: True)) – This library is free of use and lets keep it this way! Support the project. It will cost you nothing. * True: I support this project! It is even better when you occasionally click on the ethical add. * ‘text’: I support this project with a text add. * ‘image’: I support this project with an image add. * False: I want to support in a different manner: https://d3blocks.github.io/d3blocks/pages/html/Documentation.html
- Return type:
None.
References
Github : https://github.com/d3blocks/d3blocks
Movingbubbles: https://towardsdatascience.com/how-to-create-storytelling-moving-bubbles-charts-in-d3js-with-python-b31cec7b8226
Comparison of Sankey, D3graph and Heatmap: https://medium.com/@erdogant/maximize-your-insights-by-choosing-the-best-chart-network-heatmap-or-sankey-d9b4165d7f16
- static adjmat2vec(df, min_weight=1)
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
>>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example >>> df = d3.import_example('energy') >>> Convert into adjmat >>> adjmat = d3.vec2adjmat(df['source'], df['target'], df['weight']) >>> # >>> # Convert back to vector >>> vector = d3.adjmat2vec(adjmat)
- chord(df, color='source', opacity='source', ordering='ascending', fontsize=10, arrowhead=10, cmap='tab20', title='Chord - D3blocks', filepath='chord.html', figsize=[900, 900], showfig=True, overwrite=True, notebook=False, save_button=True, reset_properties=True)
Chord block.
A chord represents flows or connections between several entities or nodes. Each entity is represented by a fragment on the outer part of the circular layout. Then, arcs are drawn between each entity. The size of the arc is proportional to the importance of the flow.
- Parameters:
df (pd.DataFrame()) –
- Input data containing the following columns:
”source”
”target”
”weight”
”color” (optional)
”opacity” (optional)
color ((default: 'source')) –
- Link colors in Hex notation. Should be the same size as input DataFrame.
”source” : Color edges/links similar to that of source-color node.
”target” : Color edges/links similar to that of target-color node.
”source-target” : Color edges/link based on unique source-target edges using the colormap.
”#ffffff” : All links have the same hex color.
[“#000000”, “#ffffff”,…] : Define per link.
opacity ((default: 'source')) –
- Link Opacity. Should be the same size as input DataFrame.
’source’: Opacity of edges/links similar to that of source-opacity node.
’target’: Opacity of edges/links similar to that of target-opacity node.
0.8: All links have the same opacity.
[0.1, 0.75,…]: Set opacity per edge/link.
ordering ((default: 'ascending')) –
- Sort the labels.
’ascending’
’descending’
’’: Do not sort
[‘label1’, ‘label2’, ‘label3’]: Custom sort. Note that all labels shoul be included only once for the best result.
fontsize (int, (default: 8)) – The Fontsize.
arrowhead (int, (default: 10)) –
- The head of the arrow.
-1: No arrow
10: default
50: The larger the more pointy the arrow becomes
cmap (String, (default: 'tab20')) –
- colormap is only used in case color=None. 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’
title (String, (default: None)) –
- Title of the figure.
’Chord’
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].
[900, 900]
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
- Returns:
d3.node_properties (DataFrame of dictionary) – Contains properties of the unique input label/nodes/samples.
d3.edge_properties (DataFrame of dictionary) – Contains properties of the unique input edges/links.
d3.config (dictionary) – Contains configuration properties.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('energy') >>> # >>> # Plot >>> d3.chord(df) >>> #
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='Chord', frame=False) >>> # >>> # Import example >>> df = d3.import_example('energy') >>> # >>> # Node properties >>> d3.set_node_properties(df, opacity=0.2, cmap='tab20') >>> d3.set_edge_properties(df, color='source', opacity='source') >>> # >>> # Show the chart >>> d3.show() >>> # >>> # Make some edits to highlight the Nuclear node >>> # d3.node_properties >>> d3.node_properties.get('Nuclear')['color']='#ff0000' >>> d3.node_properties.get('Nuclear')['opacity']=1 >>> # Show the chart >>> # >>> d3.show() >>> # Make edits to highlight the Nuclear Edge >>> d3.edge_properties.loc[(d3.edge_properties['source'] == 'Nuclear') & (d3.edge_properties['target'] == 'Thermal generation'), 'color'] = '#ff0000' >>> d3.edge_properties.loc[(d3.edge_properties['source'] == 'Nuclear') & (d3.edge_properties['target'] == 'Thermal generation'), 'opacity'] = 0.8 >>> d3.edge_properties.loc[(d3.edge_properties['source'] == 'Nuclear') & (d3.edge_properties['target'] == 'Thermal generation'), 'weight'] = 1000 >>> # >>> # Show the chart >>> d3.show()
Examples
>>> # Change the order of the labels. >>> # >>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Import example >>> df = d3.import_example('energy') >>> # >>> # Custom order of the labels >>> d3.chord(df, ordering=np.sort(np.unique(df['source'].values))) >>> # >>> # Sort Ascending >>> d3.chord(df, ordering='ascending') >>> # >>> # Sort Descending >>> d3.chord(df, ordering='descending') >>> # >>> # Do not sort >>> d3.chord(df, ordering='')
References
- circlepacking(df, size: str = 'sum', zoom: str = 'click', speed: int = 750, border={'color': '#FFFFFF', 'fill': '#FFFFFF', 'padding': 5, 'width': 1.5}, font: dict = {'color': '#000000', 'outlinecolor': '#FFFFFF', 'size': 20, 'type': 'Source Serif Pro'}, title: str = 'Circlepacking - D3blocks', filepath: str = 'Circlepacking.html', figsize=[900, 1920], showfig: bool = True, overwrite: bool = True, notebook: bool = False, save_button: bool = True, reset_properties: bool = True)
Circlepacking block.
The Circlepacking chart is a visualization to hierarchically show the data as a set of nested circles. For demonstration purposes, the “energy” and “stormofswords” dataset can be used. The javascript code is forked from Mike Bostock and then Pythonized.
- Parameters:
df (pd.DataFrame()) –
- Input data containing the following columns:
’source’, ‘target’, ‘weight’
’level0’, ‘level1’, ‘level2’, ‘weight’
size (str (default: "sum")) –
- Size of the nodes can automatically be set in with:
’sum’ : This is the sum of the weights for the edges
’constant’ : All nodes are set to 1
speed (int (default: 750)) – Speed in ms to zoom in/out
zoom (str (default: "click")) –
- Zooming method.
’click’
’mouseover’
border (dict.) –
- border properties.
{‘color’: ‘#FFFFFF’, ‘width’: 1.5, ‘fill’: ‘#FFFFFF’, “padding”: 2}
border color: color for the circles
width: width for the circles
fill: fill color for the circles
padding: size of the circles
font (dict.) –
- font properties.
{‘size’: 20, ‘type’:’sans-serif’}
title (String, (default: None)) –
- Title of the figure.
’Circlepacking’
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].
[1000, 1200]
[None, None]: Use the screen resolution.
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
- Returns:
d3.node_properties (DataFrame of dictionary) – Contains properties of the unique input label/nodes/samples.
d3.edge_properties (DataFrame of dictionary) – Contains properties of the unique input edges/links.
d3.config (dictionary) – Contains configuration properties.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('energy') >>> df = d3.import_example('animals') >>> # >>> # Plot >>> d3.circlepacking(df) >>> #
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='Circlepacking', frame=True) >>> # >>> # Import example >>> df = d3.import_example('energy') >>> # >>> # Node properties >>> d3.set_node_properties(df) >>> print(d3.node_properties) >>> # >>> d3.set_edge_properties(df) >>> print(d3.edge_properties) >>> # >>> # Show the chart >>> d3.show()
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Import example >>> df = d3.import_example('energy') >>> # >>> html = d3.circlepacking(df, >>> speed=1500, >>> zoom='mouseover', >>> filepath='c://temp//circlepacking.html', >>> border={'color': '#FFFFFF', 'width': 1.5, 'fill': '#FFFFFF', "padding": 2}, >>> overwrite=True, >>> ) >>> # >>> # Show the chart >>> d3.show()
- d3graph(df, color='cluster', size='degree', opacity='degree', scaler='zscore', title='D3graph - D3blocks', filepath='d3graph.html', figsize=[1500, 800], collision=0.5, charge=400, cmap='Set1', slider=[None, None], set_slider=0, show_slider=True, notebook=False, showfig=True, support='text', save_button: bool = True, overwrite=True)
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.
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.
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.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
- 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
- display(html)
Display.
- elasticgraph(df, scaler='zscore', group='cluster', title='Elasticgraph - D3blocks', filepath='Elasticgraph.html', figsize=[1500, 800], collision=0.5, charge=250, size=4, hull_offset=15, single_click_expand=False, notebook=False, showfig=True, save_button: bool = True, overwrite=True)
D3 Elasticgraph block.
Elasticgraph is integrated in d3blocks to create interactive and stand-alone D3 force-directed graphs for which the groups are clustered. The original d3js is forked from Ger Hobbelts (see references). The input data is a dataframe containing source, target, and weight. This graph relies on the properties of d3graph and is also utilized in the d3blocks library. In underneath example, we load an example dataset which contains K relationships that are stored in a DataFrame with the columns source, target, and weight. The nodes are clustered (and 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. The ouput is a html file that is interactive and stand alone. For demonstration purposes, the “bigbang”, “energy” and “stormofswords” dataset can be used.
- Parameters:
df (pd.DataFrame()) –
- Input data containing the following columns:
’source’
’target’
’weight’
group (list of strings (default: 'cluster')) –
- Grouping (and coloring) of the nodes.
’cluster’ : Colours are based on the community distance clusters.
None: All nodes will have the same color (auto generated).
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.
size (float, (default: 4)) – Size of the nodes.
hull_offset (float, (default: 15)) – The higher the number the more the clusters will overlap after expanding.
single_click_expand (bool, (default: False)) – Nodes are not expanded with a single click.
title (String, (default: None)) –
- Title of the figure.
’elasticgraph’
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].
[None, None] # Full screen
[1500, 800]
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
- Return type:
None.
Examples
>>> # Load library >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Import example >>> df = d3.import_example('energy') # 'stormofswords' >>> # >>> # Create force-directed-network (without cluster labels) >>> d3.elasticgraph(df, filepath='Elasticgraph.html') >>> # >>> # Show elasticgraph >>> d3.Elasticgraph.show() >>> # Show original graph with the same properties >>> d3.Elasticgraph.D3graph.show() >>> # >>> # Add cluster labels (no need to do it again because it is the default) >>> # d3.Elasticgraph.set_node_properties(color=None) >>> # >>> # After making changes, show the graph again using show() >>> d3.Elasticgraph.show() >>> # Show original graph >>> d3.Elasticgraph.D3graph.show() >>> # >>> # Node properties >>> d3.Elasticgraph.D3graph.node_properties >>> # >>> # Node properties >>> d3.Elasticgraph.D3graph.edge_properties >>> #
References
- heatmap(df, scaler='zscore', color='cluster', cmap='Set2', filepath='heatmap.html', title='Heatmap - D3blocks', stroke='red', fontsize=10, fontsize_mouseover=18, description=None, cluster_params={'cluster': 'agglomerative', 'evaluate': 'silhouette', 'linkage': 'complete', 'max_clust': 25, 'metric': 'euclidean', 'min_clust': 3, 'normalize': False}, figsize=[720, 720], showfig=True, overwrite=True, notebook=False, save_button: bool = True, reset_properties=True)
Heatmap block.
heatmap is a Python package to create interactive heatmaps based on d3js. The heatmap allows interactive clustering where the cluster coloring can be customized. Clusters are colored and within each cluster the color is incremental based on the value. Adjacency matrix must be symetric.
- Parameters:
df (pd.DataFrame()) – Input data. The index and column names are used for the row/column naming.
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.
color (str or list) –
- Class label to color the clustering.
’cluster’: colors are based on clustering
’label’: colors are based on the presence of unique labels
stroke (String, (default: 'red').) –
- Color of the recangle when hovering over a cell.
’red’
’black’
fontsize (int, (default: 10)) – The fontsize of the columns and rows
fontsize_mouseover (int, (default: 10)) – The fontsize of the columns and rows with mouse-over
description (String, (default: 'Heatmap description')) – Description text of the heatmap.
cluster_params (dict (defaults)) – Parameters for clustering the data and using the cluster labels to color the heatmap. See references for more information.
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’
title (String, (default: None)) –
- Title of the figure.
’Heatmap’
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].
[800, 800]
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('stormofswords') # 'energy' >>> # >>> # Plot >>> d3.heatmap(df) >>> #
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('energy') >>> # >>> # Change cluster parameters >>> d3.heatmap(df, cluster_params={'evaluate':'dbindex', >>> 'metric':'hamming', >>> 'linkage':'complete', >>> 'normalize': False, >>> 'min_clust': 3, >>> 'max_clust': 15}) >>> #
Examples
>>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('bigbang') >>> # >>> # Plot and color on label >>> d3.heatmap(df, color=[1,1,1,2,2,2,3]) >>> d3.node_properties >>> # >>> # Plot and specify the hex color >>> d3.heatmap(df, color=['#FFF000', '#FFF000', '#FFF000', '#000FFF' , '#000FFF', '#000FFF', '#000FFF']) >>> d3.node_properties
References
- imageslider(img_before, img_after, scale=True, colorscale=-1, background='#000000', title='Imageslider - D3blocks', filepath='imageslider.html', figsize=[None, None], showfig=True, notebook=False, overwrite=True)
Imageslider Block.
The imageslider allows comparison of two images. This is useful in case there is a before and after state. For demonstration purposes, the example can be loaded from the Southern Nebula image that is taken with the Hubble telescope, and can be easily compared to that of the newest telescope. The javascript code is forked from JohnEdChristensen and then Pythonized to easily make comparisons between images.
- Parameters:
img_before (String) – absolute path to before image.
img_after (String) – absolute path to after image.
scale (bool, default: True) –
- Scale image in range [0, 255], by img*(255/max(img))
True: Scaling image
False: Leave image untouched
colorscale (int, default: -1 (untouched)) –
- colour-scaling from opencv.
0: cv2.IMREAD_GRAYSCALE
1: cv2.IMREAD_COLOR
2: cv2.IMREAD_ANYDEPTH
8: cv2.COLOR_GRAY2RGB
-1: cv2.IMREAD_UNCHANGED
background (String (default: '#000000')) – Background color.
title (String, (default: None)) –
- Title of the figure.
’Imageslider’
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].
[900, 900]
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
- Return type:
None.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Local images >>> img_before, img_after = d3.import_example('southern_nebula') >>> # >>> # Internet location >>> img_before, img_after = d3.import_example('southern_nebula_internet') >>> # >>> # Read the image in array >>> img_before = cv2.imread(img_before, -1) >>> img_after = cv2.imread(img_after, -1) >>> # >>> # Plot >>> d3.imageslider(img_before, img_after) >>> # >>> # Plot >>> d3.imageslider(img_before, img_after, showfig=True, scale=True, colorscale=2, figsize=[400, 400])
References
- import_example(data, n=10000, c=300, date_start='17-12-1903 00:00:00', date_stop='17-12-1903 23:59:59', overwrite=False)
Import example dataset from github source.
Import one of the few datasets from github sourcek.
- Parameters:
data (str) –
- Example datasets:
”movingbubbles”
”random_time”
”timeseries”
”bigbang”
”southern_nebula_internet”
”climate”
”mnist”
”animals”
- Datazets:
”energy”
”stormofswords”
”southern_nebula”
”cancer”
”breast_cancer”
”iris”
”occupancy”
n (int, (default: 1000).) – Number of events (samples).
c (int, (default: 100).) – Number of classes.
date_start (str, (default: None)) –
- Start date.
”17-12-1903 00:00:00” : start date
date_stop (str, (default: None)) –
- Stop date.
”17-12-1903 23:59:59” : Stop date
- Returns:
Dataset containing mixed features.
- Return type:
pd.DataFrame()
- maps(df, size=10, color='#0981D1', opacity=0.8, label='', countries={'Australia': {'color': '#008000', 'line': 'dashed', 'linewidth': 5, 'opacity': 0.3}, 'World': {'color': '#D3D3D3', 'line': 'none', 'linewidth': 1, 'opacity': 0.6}}, cmap='Set2', title: str = 'Maps - D3blocks', filepath: str = 'maps.html', figsize=None, showfig: bool = True, overwrite: bool = True, notebook: bool = False, save_button: bool = True, reset_properties: bool = True)
Maps block.
The Maps chart is a visualization to plot the World and color and mark countries together with circles for highlighs. For demonstration purposes, the “surfspots” can be used. The javascript code is forked from Mike Bostock and then Pythonized.
- Parameters:
df (pd.DataFrame()) –
- Input data containing the following columns:
’lon’, ‘lat’, ‘label’, ‘size’, ‘opacity’
size (str (default: 10)) –
- Size of the nodes:
10 : Same size for all scatter points
[10, 4, 30, ..]
color (str (default: '#0981D1')) –
- Hex color of the scatter points:
’#0981D1’: Same color for all scatter points
[‘Netherlands’, ‘Australia’, ‘Austrialia’, ..]
[‘#000FFF’, ‘#000000’, ‘#000000’, ..]
opacity (str (default: 0.8)) –
- Opacity of the scatter points:
0.8 : Same opacity for all scatter points
[0.8, 0.6, ..]
label (str (default: '')) –
- Label of the scatter points:
’’ : Same label for all scatter points
[‘Amsterdam’, ‘New York’, ..]
countries (dict.) –
- border properties of the countries. The world are the properties of the entire map. Each country can be changed accordingly.
{‘World’: {‘color’:’#D3D3D3’, ‘opacity’: 0.3, ‘line’: ‘none’, ‘linewidth’: 1}},
color: color for the country
opacity: opacity of the country
line: [‘dashed’, ‘none’], line of the country
linewidth: width of the line
title (String, (default: None)) –
- Title of the figure.
’Circlepacking’
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].
[1000, 1200]
None or [None, None]: Use the screen resolution.
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
- Returns:
d3.node_properties (DataFrame of dictionary) – Contains properties of the unique input label/nodes/samples.
d3.edge_properties (DataFrame of dictionary) – Contains properties of the unique input edges/links.
d3.config (dictionary) – Contains configuration properties.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('surfspots') >>> # >>> # Plot >>> d3.maps(df) >>> #
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('surfspots') >>> # >>> # Plot >>> d3.maps(df, color=df['label'].values, cmap='Set2') >>> # >>> html = d3.maps(df, color=df['label'].values, countries = {'World': {'color':'#D3D3D3', 'opacity': 0.4, 'line': 'none', 'linewidth': 0.1}, >>> 'Netherlands': {'color': '#000FFF', 'opacity': 0.5, 'line': 'none', 'linewidth': 1}, >>> 'France': {'color': '#FFA500', 'opacity': 1, 'line': 'dashed', 'linewidth': 2}, >>> 'Australia': {'color': '#008000', 'opacity': 0.3, 'line': 'dashed', 'linewidth': 5}, >>> })
Examples
>>> # Load library >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='maps', frame=False) >>> # >>> # Import example >>> df = d3.import_example('surfspots', overwrite=True) >>> # >>> # Set node properties >>> d3.set_node_properties(df) >>> d3.node_properties >>> # >>> # Set edge properties >>> d3.set_edge_properties({'Australia': {'color': '#008000', 'opacity': 0.3, 'line': 'dashed', 'linewidth': 5}, >>> 'Netherlands': {'color': '#000FFF', 'line': 'dashed'}, >>> }) >>> d3.edge_properties >>> # >>> # Show chart >>> d3.show() >>> #
- matrix(df, scale=False, stroke='red', description=None, vmin=None, vmax=None, cmap='interpolateInferno', fontsize=10, title='Matrix - D3blocks', figsize=[700, 500], showfig=True, filepath='matrix.html', overwrite=True, notebook=False, save_button: bool = True, reset_properties=True)
Matrix block.
- Parameters:
df (pd.DataFrame()) – Input data. The index and column names are used for the row/column naming.
scale (Bool, (default: True).) –
- Scale data in range Scaling in range by X*(100/max(X)).
True: Scale the values.
False: Do not scale.
stroke (String, (default: 'red').) –
- Color of the recangle when hovering over a cell.
’red’
’black’
description (String.) – Description text of the heatmap.
vmax (Bool, (default: 100).) –
- Range of colors starting with maximum value. Increasing this value will color the cells more discrete.
1 : cells above value >1 are capped.
None : cells are colored based on the maximum value in the input data.
cmap (String, (default: 'interpolateInferno').) –
- The colormap scheme. See references for more schmes.
’interpolateInferno’
’interpolatePRGn’
’interpolateBlues’
’interpolateGreens’
’interpolateTurbo’
’interpolateViridis’
’interpolateInferno’
’interpolateRainbow’
’interpolateSinebow’
fontsize (int, (default: 10).) – Font size for the X and Y labels.
title (String, (default: None)) –
- Title of the figure.
’Heatmap’
figsize (tuple) –
- Size of the figure in the browser, [width, height].
[800, 800]
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
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
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
Examples
>>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = pd.DataFrame(np.random.randint(0, 10, size=(6, 20))) >>> # >>> # Plot >>> d3.matrix(df) >>> # >>> d3.matrix(df, vmin=1, fontsize=10, title='D3blocks Matrix', figsize=[600, 300], cmap='interpolateGreens', filepath='matrix.html', )
References
- movingbubbles(df, datetime: str = 'datetime', sample_id: str = 'sample_id', state: str = 'state', center: str = None, size=5, color=None, cmap: str = 'Set1', color_method: str = 'state', dt_format: str = '%d-%m-%Y %H:%M:%S', damper: float = 1, fontsize: int = 14, timedelta: str = 'minutes', standardize: str = 'samplewise', speed: dict = {'fast': 50, 'medium': 200, 'slow': 1000}, figsize=[700, 800], note: str = None, time_notes: str = None, title: str = 'Movingbubbles - D3Blocks', filepath: str = 'movingbubbles.html', showfig: bool = True, overwrite: bool = True, notebook: bool = False, save_button: bool = True, reset_properties: bool = True)
Movingbubbles block.
The MovingBubbles provides insights into when one action follows the other across time. It can help to understand the movements of entities, and whether clusters occur at specific time points and state(s). It may not be the most visually efficient method, but it is one of the more visually satisfying ones with force-directed and colliding nodes. The function d3.import_example(‘random_time’) is created to generate a randomized dataset with various states. The input dataset should contain 3 columns;
DateTime column: Describes the data-time when an event occurs.
State column: Describes what the particular state was at that point of time of the specific sample_id.
Sample_id column: A sample can have multiple states at various time points but can not have two states at exactly the same point in time.
- Parameters:
df (Input data, pd.DataFrame()) – Input data.
datetime (str, (default: 'datetime')) – Name of the column with the datetime.
sample_id (str, (default: 'sample_id')) – Name of the column with the sample ids.
state (str, (default: 'state')) – Name of the column with the states.
center (String, (default: None)) – Center this category.
size (int or dictionary. (default: 5) or {sample_id i: size}) –
- Size the nodes by specifying per sample_id the size.
5: set all nodes this this size
{‘0’: 4, ‘1’: 10, ‘2’: 5, ..}: Specify size for each sample_id
color (int or dictionary. (default: '#808080') or {sample_id i: hex-color}) –
- Color the nodes by specifying per sample_id the color.
’#000FFF’: set all nodes to this color.
{‘0’: ‘#808080’, ‘1’: ‘#FFF000’, ‘3’: ‘#000000’, ..}: Specify color for each sample_id
None: Colors are based on sample_id using the cmap.
color_method (str) –
- Coloring of the nodes.
’state’: Use the colors defined per state as (d3.node_properties).
’node’: Use the colors defined in the dataframe (d3.edge_properties).
dt_format (str) –
- Date time format.
’%d-%m-%Y %H:%M:%S’.
damper (float, (default: 1)) –
- Movement of samples. A smaller number is slower/smoother movement.
0.1: min
10: max
fontsize (int, (default: 14)) – Fontsize of the states.
timedelta (String, (default: 'minutes')) –
- The time delta between states. Change accordingly.
’seconds’
’minutes’
’days’
standardize (str. (default: None)) –
- Method to standardize the data.
None: standardize over the entire timeframe. Sample_ids are dependent to each other.
’samplewise’: Standardize per sample_id by substracting the minimum time per sample_id.
’relative’: Standardize across the entire dataframe after sorting on time. Each action is relative to the previous one in time without considering sample_id.
’minimum’: Movements are relative to the minimum time in the dataset.
speed (dict, (default: {"slow": 1000, "medium": 200, "fast": 50})) – The final html file contains three buttons for speed movements. The lower the value, the faster the time moves.
note (str, (default: None)) –
- A specific note, such as project description can be put on the html page.
None: Default text will be provided about the simulation, and states.
time_notes (dict, (default: None)) –
- The time notes will be shown between specific time points.
- time_notes = [{“start_minute”: 1,
”stop_minute”: 5, “note”: “Enter your note here and it is shown between 1 min and 5 min.”}]
time_notes.append[{“start_minute”: 6, “stop_minute”: 10, “note”: “Enter your second note here and it is shown between 6 min and 10 min.”}]
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’
title (String, (default: None)) –
- Title of the figure.
’Movingbubbles’
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].
[780, 800]
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
- Returns:
d3.node_properties (DataFrame of dictionary) – Contains properties of the unique input label/nodes/samples.
d3.edge_properties (DataFrame of dictionary) – Contains properties of the unique input edges/links.
d3.config (dictionary) – Contains configuration properties.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('random_time', n=10000, c=300, date_start="1-1-2000 00:10:05", date_stop="1-1-2000 23:59:59") >>> # >>> # Plot >>> d3.movingbubbles(df, speed={"slow": 1000, "medium": 200, "fast": 10}, filepath='movingbubbles.html') >>> #
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='movingbubbles', frame=False) >>> # >>> # Import example >>> df = d3.import_example('random_time', n=1000, c=100, date_start="1-1-2000 00:10:05", date_stop="1-1-2000 23:59:59") >>> # >>> # Coloring the states. >>> d3.set_node_properties(df['state']) >>> print(d3.node_properties) >>> # Color the sleeping state black >>> d3.node_properties.get('Sleeping')['color']='#000000' >>> # >>> d3.set_edge_properties(df) >>> print(d3.edge_properties) >>> # >>> # Show >>> d3.show(title='Movingbubbles with adjusted configurations')
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='movingbubbles') >>> # >>> # Import example >>> df = d3.import_example('random_time', n=1000, c=100, date_start="1-1-2000 00:10:05", date_stop="1-1-2000 23:59:59") >>> # >>> # Specify the colors and node sizes for the specific sample_id >>> size = {1: 20, 3: 40} >>> color = {1: '#FF0000', 3: '#000FFF'} >>> # >>> # Show >>> d3.movingbubbles(df, color=color, size=size)
References
- open_browser(sleep=0.2, logger=None)
Open browser to show chart.
- particles(text: str, radius: int = 3, collision: float = 0.05, fontsize: int = 180, spacing: int = 8, cmap: str = 'Turbo', color_background: str = '#000000', title: str = 'Particles - D3blocks', filepath: str = 'particles.html', figsize=[900, 200], showfig: bool = True, notebook: bool = False, save_button: bool = False, overwrite: bool = True)
Particles block.
The particles plot is to turn any word into an interactive visualization. With a mouse-move or touch, the particle bounce and then return to their original place. Various properties can be changed such as the bouncing, particle size, and colors. The original javascript is forked from Ian Johnson’s Block.
- Parameters:
text (str) – String to be visualized
radius (float, optional (default: 3)) – Size of the particles.
collision (float, optional (default: 0.1)) – Response of the interaction. Higher means that more collisions are prevented.
fontsize (int, optional (default: 250)) – Text fontsize. When increasing: also increase width and slighly the spacing.
spacing (int, optional (default: 10)) – The number of particles that fit in the text. A larger spacing reults in less particles. A smaller spacing reults in more particles.
cmap (str, optional (default: 'Set2')) –
- Color schemes can be found at the references.
’Turbo’, ‘Rainbow’, ‘Blues’, ‘Reds’, ‘Inferno’, ‘Magma’
color_background (str, optional (default: '#000000')) – Background color.
title (str, optional (default: None)) – Title of the figure.
filepath (str, optional (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 content.
figsize (tuple, optional (default: (800, 600))) – Size of the figure in the browser, [width, height].
showfig (bool, optional (default: True)) – Open the window to show the particles.
notebook (bool, optional) –
True: Use IPython to show chart in notebooks.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
overwrite (bool, optional (default: True)) –
True: Overwrite the output html in the destination directory.
False: Do not overwrite
- Return type:
None.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Create chart with defaults >>> d3.particles('D3blocks') >>> # >>> # Create customized chart >>> d3.particles('D3Blocks', filepath='D3Blocks.html', collision=0.05, spacing=7, figsize=[750, 150], fontsize=130, cmap='Turbo', color_background='#ffffff')
References
- sankey(df, color=None, node={'align': 'justify', 'color': 'currentColor', 'padding': 15, 'width': 15}, link={'color': 'source-target', 'color_static': '#d3d3d3', 'stroke_opacity': 0.5}, margin={'bottom': 5, 'left': 1, 'right': 1, 'top': 5}, fontsize: int = 10, title='Sankey - D3blocks', filepath='sankey.html', figsize=[800, 600], showfig=True, overwrite=True, notebook=False, save_button: bool = True, reset_properties=True)
Sankey block.
A Sankey chart is a visualization to depict a flow from one set of values to another. The nodes in this case are represented as the rectangle boxes, and the flow or arrows are the links. The width of the arrow is proportional to the flow rate. Sankeys are best used when you want to show many-to-many relationships or to discover multiple paths through a set of stages. For example, the traffic flows from pages to other pages on your website. For demonstration purposes, the “energy” and “stormofswords” dataset can be used. The javascript code is forked from Mike Bostock and then Pythonized.
- Parameters:
df (pd.DataFrame()) –
- Input data containing the following columns:
’source’
’target’
’weight’
color (dict or None.) –
- Dictionary containing node with color information.
color={‘Nuclear’: ‘#FF0000’, ‘Wind’:’#FF0000’}
link (dict.) –
- Dictionary containing edge or link information.
”linkColor” : “source”, “target”, “source-target”
”linkStrokeOpacity” : 0.5
”color_static”: ‘#0f0f0f’ or “grey”, “blue”, “red” etc
fontsize (int or dict.) –
10 : All nodes get this fontsize
{‘Nuclear’: 10, ‘Wind’: 20}
margin (dict.) –
- margin, in pixels.
”top” : 5
”right” : 1
”bottom” : 5
”left” : 1
node (dict.) –
“align” : “left”, “right”, “justify”, “center”
”width” : 15 (width of the node rectangles)
”padding” : 15 (vertical seperation between the nodes)
”color” : “currentColor”, “grey”, “black”, “red”, etc
title (String, (default: None)) –
- Title of the figure.
’Sankey’
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].
[800, 600]
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
- Returns:
d3.node_properties (DataFrame of dictionary) – Contains properties of the unique input label/nodes/samples.
d3.edge_properties (DataFrame of dictionary) – Contains properties of the unique input edges/links.
d3.config (dictionary) – Contains configuration properties.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('energy') >>> # >>> # Plot >>> d3.sankey(df) >>> #
Examples
>>> # Adjust node and edge properties >>> # >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='Sankey', frame=True) >>> # >>> # Import example >>> df = d3.import_example('energy') >>> # >>> # Node properties >>> d3.set_node_properties(df) >>> print(d3.node_properties) >>> # >>> d3.set_edge_properties(df, color='target', opacity='target') >>> print(d3.edge_properties) >>> # >>> # Show the chart >>> d3.show()
Examples
>>> # Create Custom colors >>> # >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='Sankey', frame=True) >>> # >>> # Import example >>> df = d3.import_example('energy') >>> # >>> # Custom color the nodes >>> html = d3.sankey(df.copy(), filepath=r'c://temp//sankey.html', color={'Nuclear': '#FF0000', 'Wind':'#000000', 'Electricity grid':'#FF0000'}) >>> # >>> # Alternatively: >>> d3 = D3Blocks(chart='Sankey', frame=True) >>> df = d3.import_example(data='energy') >>> d3.set_node_properties(df, color={'Nuclear': '#FF0000', 'Wind':'#FF0000', 'Electricity grid':'#7FFFD4', 'Bio-conversion':'#000000', 'Industry': '#000000'}) >>> d3.set_edge_properties(df, color='target', opacity='target') >>> d3.show(filepath=r'c://temp//sankey.html') >>> #
References
- scatter(x, y, x1=None, y1=None, x2=None, y2=None, jitter=None, size=3, color='#002147', c_gradient='opaque', opacity=0.8, stroke='#ffffff', tooltip=None, cmap='tab20', scale=False, color_background='#ffffff', label_radio=['(x, y)', '(x1, y1)', '(x2, y2)'], xlim=[None, None], ylim=[None, None], title='Scatter - D3blocks', filepath='scatter.html', figsize=[900, 600], showfig=True, overwrite=True, notebook=False, save_button: bool = True, reset_properties=True)
Scatterplot block.
The scatter plot is perhaps the most well-known chart to plot x, and y coordinates. Basic charts are very useful from time to time, especially with the brushing and zooming capabilities. The scatter plots can be sample-wise colored and used to detect relationships between (groups of) variables. The input data frame should contain 2 columns (x and y) with the coordinates, and the index represents the class label.
- Parameters:
x (numpy array) – 1d coordinates x-axis.
y (numpy array) – 1d coordinates y-axis.
x1 (numpy array) – Second set of 1d coordinates x-axis.
y1 (numpy array) – Second set of 1d coordinates y-axis.
x2 (numpy array) – Third set of 1d coordinates x-axis.
y2 (numpy array) – Third set of 1d coordinates y-axis.
jitter (float, default: None) – Add jitter to data points as random normal data. Values of 0.01 is usually good for one-hot data seperation.
size (list/array of with same size as (x,y).) – Size of the samples.
color (list/array of hex colors with same size as (x,y)) –
‘#ffffff’ : All dots are get the same hex color.
None: The same color as for c is applied.
[‘#000000’, ‘#ffffff’,…]: list/array of hex colors with same size as (x,y)
stroke (list/array of hex colors with same size as (x,y)) –
- Edgecolor of dotsize in hex colors.
’#000000’ : All dots are get the same hex color.
[‘#000000’, ‘#ffffff’,…]: list/array of hex colors with same size as (x,y)
c_gradient (String, (default: 'opaque')) –
- Hex color to make a lineair gradient using the density.
None: Do not use gradient.
opaque: Towards the edges the points become more transparant. This will stress the dense areas and make scatter plot tidy.
’#FFFFFF’: Towards the edges it smooths into this color
opacity (float or list/array [0-1]) – Opacity of the dot. Shoud be same size as (x,y)
tooltip (list of labels with same size as (x,y)) – labels of the samples.
cmap (String, (default: 'inferno')) –
- 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’
scale (Bool, optional) – Scale datapoints. The default is False.
label_radio (List ['(x, y)', '(x1, y1)', '(x2, y2)']) – The labels used for the radiobuttons.
set_xlim (tuple, (default: [None, None])) – Width of the x-axis: The default is extracted from the data with 10% spacing.
set_ylim (tuple, (default: [None, None])) – Height of the y-axis: The default is extracted from the data with 10% spacing.
title (String, (default: None)) –
- Title of the figure.
’Scatterplot’
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].
[900, 600]
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
- Returns:
d3.node_properties (DataFrame of dictionary) – Contains properties of the unique input label/nodes/samples.
d3.edge_properties (DataFrame of dictionary) – Contains properties of the unique input edges/links.
d3.config (dictionary) – Contains configuration properties.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('cancer') >>> # >>> # Set size and tooltip >>> size = df['survival_months'].fillna(1).values / 20 >>> tooltip = df['labx'].values + ' <br /> Survival: ' + df['survival_months'].astype(str).str[0:4].values >>> # >>> # Scatter plot >>> d3.scatter(df['tsneX'].values, df['tsneY'].values, size=size, color=df['labx'].values, stroke='#000000', opacity=0.4, tooltip=tooltip, filepath='scatter_demo.html', cmap='tab20')
Examples
>>> # Scatter plot with transitions. Note that scale is set to True to make the axis comparible to each other >>> d3.scatter(df['tsneX'].values, df['tsneY'].values, x1=df['PC1'].values, y1=df['PC2'].values, label_radio=['tSNE', 'PCA'], scale=True, size=size, color=df['labx'].values, stroke='#000000', opacity=0.4, tooltip=tooltip, filepath='scatter_transitions2.html', cmap='tab20')
Examples
>>> # Scatter plot with transitions. Note that scale is set to True to make the axis comparible to each other >>> d3.scatter(df['tsneX'].values, df['tsneY'].values, x1=df['PC1'].values, y1=df['PC2'].values, x2=df['PC2'].values, y2=df['PC1'].values, label_radio=['tSNE', 'PCA', 'PCA_reverse'], scale=True, size=size, color=df['labx'].values, stroke='#000000', opacity=0.4, tooltip=tooltip, filepath='scatter_transitions3.html', cmap='tab20')
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='Scatter') >>> # >>> # Import example >>> df = d3.import_example('cancer') >>> # >>> # Set properties >>> d3.set_edge_properties(df['tsneX'].values, df['tsneY'].values, x1=df['PC1'].values, y1=df['PC2'].values, label_radio=['tSNE','PCA'], size=df['survival_months'].fillna(1).values / 10, color=df['labx'].values, tooltip=df['labx'].values + ' <br /> Survival: ' + df['survival_months'].astype(str).str[0:4].values, scale=True) >>> # >>> # Show the chart >>> d3.show() >>> # >>> # Set specific node properties. >>> print(d3.edge_properties) >>> d3.edge_properties.loc[0,'size']=50 >>> d3.edge_properties.loc[0,'color']='#000000' >>> d3.edge_properties.loc[0,'tooltip']='I am adjusted!' >>> # >>> # Configuration can be changed too. >>> print(d3.config) >>> # >>> # Show the chart again with adjustments >>> d3.show()
References
- set_config()
Set the general configuration setting.
- set_edge_properties(*args, **kwargs)
Set edge properties.
The input for edge properties are the arguments that are inherited from the chart-function. As an example, the edge properties for the scatter chart are those described in the scatter function.
- Parameters:
df (pd.DataFrame()) –
- Input data containing the following columns:
’source’
’target’
’weight’
’color’ (optional)
’opacity’ (optional)
color (Union[float, List[float]], optional) –
- Link colors in Hex notation. Should be the same size as input DataFrame.
None : ‘cmap’ is used to create colors.
’source’: Color edges/links similar to that of source-color node.
’target’: Color edges/links similar to that of target-color node.
’source-target’: Color edges/link based on unique source-target edges using the colormap.
’#ffffff’: All links have the same hex color.
[‘#000000’, ‘#ffffff’,…]: Define per link.
opacity (float or list/array [0..1] (default: None)) –
- Link Opacity. Should be the same size as input DataFrame.
’source’: Opacity of edges/links similar to that of source-opacity node.
’target’: Opacity of edges/links similar to that of target-opacity node.
0.8: All links have the same opacity.
[0.1, 0.75,…]: Set opacity per edge/link.
cmap (String, (default: 'tab20')) –
colormap is only used in case color=None. 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’
- Return type:
None.
- set_node_properties(*args, **kwargs)
Set label properties.
- Parameters:
labels (array-like (default: None)) –
- The unique names of the nodes/labels.
In case of pd.DataFrame, the ‘source’ and ‘target’ columns are used.
- Returns:
labels – Dictionary containing class information.
- Return type:
dict()
- show(**kwargs) None
Build and show the graph.
- Parameters:
figsize (tuple) – Size of the figure in the browser, [height, width].
title (String, (default: None)) – Title of the figure.
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
showfig (bool) –
True: Open the browser and show chart.
False: Do not open browser.
notebook (bool) –
True: Use IPython to show chart in notebooks.
False: Do not use IPython.
kwargs (Various) – Other options are possible depending on the chart that is being used.
- Return type:
None.
- timeseries(df, datetime='datetime', dt_format: str = '%d-%m-%Y %H:%M:%S', sort_on_date=True, whitelist=None, fontsize=10, cmap='Set1', title='Timeseries - D3blocks', filepath='timeseries.html', figsize=[1200, 500], showfig=True, overwrite=True, notebook=False, save_button: bool = True, reset_properties=True)
Timeseries block.
The TimeSeries can be used in case a date-time element is available, and where the time-wise values directly follow up with each other. The TimeSeries block supports enabling/disabling columns of interest, brushing and zooming to quickly focus on regions of interest or plot specific features, such as stocks together in a single chart.
- Parameters:
df (pd.DataFrame()) – Input data containing the columns “datetime” together with the names of the timeseries to plot.
datetime (str, (default: None)) – Column name that contains the datetime.
dt_format (str) –
- Date time format.
’%d-%m-%Y %H:%M:%S’.
sort_on_date (Bool (default: True)) –
- Sort on date.
True: Sort on datetime.
False: Do not change the input order.
whitelist (str, optional) – Keep only columns containing this (sub)string (case insensitive)
fontsize (int, (default: 14)) – Fontsize of the fonts in the circle.
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’
title (String, (default: None)) –
- Title of the figure.
’Timeseries’
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].
[1200, 500]
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
- Returns:
d3.node_properties (DataFrame of dictionary) – Contains properties of the unique input label/nodes/samples.
d3.edge_properties (DataFrame of dictionary) – Contains properties of the unique input edges/links.
d3.config (dictionary) – Contains configuration properties.
Examples
>>> # >>> # Import >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Import example >>> df = d3.import_example('climate') >>> # >>> # Show >>> d3.timeseries(df, datetime='date', dt_format='%Y-%m-%d %H:%M:%S', fontsize=10, figsize=[850, 500]) >>> #
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='Timeseries', frame=False) >>> # >>> # Import example >>> df = d3.import_example('climate') >>> # >>> # Node properties >>> d3.set_node_properties(df.columns.values) >>> d3.node_properties.get('wind_speed')['color']='#000000' >>> print(d3.node_properties) >>> # >>> d3.set_edge_properties(df, datetime='date', dt_format='%Y-%m-%d %H:%M:%S') >>> d3.edge_properties >>> # >>> # Show >>> d3.show(title='Timeseries with adjusted configurations') >>> #
References
- tree(df: DataFrame, hierarchy=[1, 2, 3, 4, 5, 6, 7, 8], margin={'bottom': 20, 'left': 60, 'right': 80, 'top': 20}, font={'size': 10}, title: str = 'Tree - D3blocks', filepath: str = 'tree.html', figsize=[960, 700], showfig: bool = True, overwrite: bool = True, notebook: bool = False, save_button: bool = True, reset_properties: bool = True)
Tree block.
A Tree chart is a visualization to hierarchically show the data. For demonstration purposes, the “energy” dataset can be used. The javascript code is forked from Mike Bostock, inspired by R-Shiny and then Pythonized.
- Parameters:
df (pd.DataFrame()) –
- Input data containing the following columns:
’source’, ‘target’, ‘weight’
hierarchy (list) – Expand or substract the hierarchical structure. No information is lossed. The eight branches are shown by default. * [1, 2, 3, 4, 5, 6, 7, 8]
margin (dict.) –
- margin, in pixels.
{“top”: 40, “right”: 10, “bottom”: 10, “left”: 10}
font (dict.) –
- font properties.
{‘size’: 10}
title (String, (default: None)) –
- Title of the figure.
’Treemap’
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].
[1000, 600]
[None, None]: Use the screen resolution.
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
- Returns:
d3.node_properties (DataFrame of dictionary) – Contains properties of the unique input label/nodes/samples.
d3.edge_properties (DataFrame of dictionary) – Contains properties of the unique input edges/links.
d3.config (dictionary) – Contains configuration properties.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('energy') >>> # >>> # Plot >>> d3.tree(df) >>> #
Examples
>>> # Load library >>> from d3blocks import D3Blocks >>> >>> # Initialize >>> d3 = D3Blocks(verbose='info', chart='tree', frame=False) >>> >>> # Import example >>> df = d3.import_example('energy') >>> >>> # Set node properties >>> d3.set_node_properties(df) >>> >>> # Set specific properties >>> d3.node_properties.get('Bio-conversion')['size'] = 30 >>> d3.node_properties.get('Bio-conversion')['color'] = '#000000' >>> d3.node_properties.get('Bio-conversion')['tooltip'] = 'Title: P Operations<br><img src="https://source.unsplash.com/collection/385548/150x100">' >>> d3.node_properties.get('Bio-conversion')['edge_color'] = '#00FFFF' >>> d3.node_properties.get('Bio-conversion')['edge_size'] = 5 >>> d3.node_properties.get('Bio-conversion')['opacity'] = 0.4 >>> >>> # Set properties for Losses >>> d3.node_properties.get('Losses')['color'] = '#FF0000' >>> d3.node_properties.get('Losses')['size'] = 15 >>> d3.node_properties.get('Losses')['tooltip'] = '' >>> >>> # Set properties for Agriculture >>> d3.node_properties.get('Agriculture')['color'] = '#00FFFF' >>> d3.node_properties.get('Agriculture')['size'] = 5 >>> d3.node_properties.get('Agriculture')['edge_color'] = '#89CFF0' >>> d3.node_properties.get('Agriculture')['edge_size'] = 3 >>> d3.node_properties.get('Agriculture')['opacity'] = 0.7 >>> >>> # Set edge properties >>> d3.set_edge_properties(df) >>> >>> # Show chart >>> d3.show(hierarchy=[1, 2, 3, 4, 5, 6, 7, 8], filepath=r'c://temp//tree.html')
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='tree', frame=True) >>> # >>> # Import example >>> df = d3.import_example('energy') >>> # >>> # Node properties >>> d3.set_node_properties(df) >>> print(d3.node_properties) >>> # >>> d3.set_edge_properties(df) >>> print(d3.edge_properties) >>> # >>> # Show the chart >>> d3.show()
References
- treemap(df: DataFrame, margin={'bottom': 10, 'left': 10, 'right': 10, 'top': 40}, border={'color': '#FFFFFF', 'type': 'solid', 'width': 1}, font={'position': 'absolute', 'size': 10, 'type': 'sans-serif'}, title: str = 'Treemap - D3blocks', filepath: str = 'treemap.html', figsize=[1000, 600], showfig: bool = True, overwrite: bool = True, notebook: bool = False, reset_properties: bool = True)
Treemap block.
A Treemap chart is a visualization to hierarchically show the data as a set of nested rectangles. For demonstration purposes, the “energy” and “stormofswords” dataset can be used. The javascript code is forked from Mike Bostock and then Pythonized.
- Parameters:
df (pd.DataFrame()) –
- Input data containing the following columns:
’source’, ‘target’, ‘weight’
’level0’, ‘level1’, ‘level2’, ‘weight’
margin (dict.) –
- margin, in pixels.
{“top”: 40, “right”: 10, “bottom”: 10, “left”: 10}
border (dict.) –
- border properties.
{‘type’: ‘solid’, ‘color’: ‘#FFFFFF’, ‘width’: 1}
font (dict.) –
- font properties.
{‘size’: 10, ‘type’:’sans-serif’, ‘position’: ‘absolute’}
title (String, (default: None)) –
- Title of the figure.
’Treemap’
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].
[1000, 600]
[None, None]: Use the screen resolution.
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
- Returns:
d3.node_properties (DataFrame of dictionary) – Contains properties of the unique input label/nodes/samples.
d3.edge_properties (DataFrame of dictionary) – Contains properties of the unique input edges/links.
d3.config (dictionary) – Contains configuration properties.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example data >>> df = d3.import_example('energy') >>> df = d3.import_example('animals') >>> # >>> # Plot >>> d3.treemap(df) >>> #
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks(chart='Treemap', frame=True) >>> # >>> # Import example >>> df = d3.import_example('energy') >>> # >>> # Node properties >>> d3.set_node_properties(df) >>> print(d3.node_properties) >>> # >>> d3.set_edge_properties(df) >>> print(d3.edge_properties) >>> # >>> # Show the chart >>> d3.show()
Examples
>>> # Add tooltip >>> # >>> # Intialize Treemap >>> from d3blocks import D3Blocks >>> d3 = D3Blocks(chart='treemap', frame=False) >>> # >>> # Import example >>> df = d3.import_example('energy') >>> # >>> # Set node properties >>> d3.set_node_properties(df) >>> # >>> # Set tooltip for specific nodes >>> d3.node_properties['Bio-conversion']['tooltip'] = 'Title: Bio conversion Operations' >>> d3.node_properties.get('Losses')['tooltip'] = 'losses tooltip' >>> # >>> # Set edge properties >>> d3.set_edge_properties(df) >>> # >>> # Show chart >>> d3.show(filepath=r'c://temp//treemap.html')
References
- static vec2adjmat(source, target, weight=None, symmetric=True, aggfunc='sum')
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
>>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Load example >>> df = d3.import_example('energy') >>> # >>> # Convert to adjmat >>> adjmat = d3.vec2adjmat(df['source'], df['target'], df['weight'])
- violin(x, y, size=5, color=None, x_order=None, opacity=0.6, stroke='#000000', tooltip=None, fontsize=12, fontsize_axis: int = 12, cmap: str = 'inferno', bins: int = 50, ylim=[None, None], title: str = 'Violin - D3blocks', filepath='violin.html', figsize=[None, None], showfig: bool = True, overwrite: bool = True, notebook: bool = False, save_button: bool = True, reset_properties: bool = True)
Violin block.
The Violin plot allows to visualize the distribution of a numeric variable for one or several groups. It is an alternative to the boxplot and brings insights into large datasets where the boxplot could hide a part of the information. The original javascript code is forked from D3.js graph gallery but brought alive by Pythonizing the chart. Now it is possible to configure your charts for one or several groups, change colors, add tooltips, customize the bin size, change figure size and store on a specified location. There are many input parameters for the Violin plot that can help to create the most insightful figures.
- Parameters:
x (list of String or numpy array.) – This 1d-vector contains the class labels for each datapoint in y.
y (list of float or numpy array.) – This 1d-vector contains the values for the samples.
size (list/array of with same size as (x,y). Can be of type str or int.) – Size of the samples.
color (list/array of hex colors with same size as y) –
‘#002147’ : All dots/nodes are get the same hex color.
None: The colors are generated on value using the colormap specified in cmap.
[‘#000000’, ‘#ffffff’,…]: list/array of hex colors with same size as y.
x_order (list of String (default: None)) –
- The order of the class labels on the x-axis.
[“setosa”, “versicolor”, “virginica”]
opacity (float or list/array [0-1] (default: 0.6)) – Opacity of the dot. Shoud be same size as (x,y)
stroke (list/array of hex colors with same size as (x,y)) –
- Edgecolor of dot in hex colors.
’#000000’ : Edge colors are all black.
tooltip (list of labels with same size as (x,y)) – labels of the samples.
fontsize (int or list of labels with the same size as (x, y), optional (default: 12)) – Text fontsize for the tooltip.
fontsize_axis (int, optional (default: 12)) – Text fontsize for the x-axis and y-axis.
cmap (String, (default: 'inferno')) –
- 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’
bins (Int (default: 50)) – The bin size is the ‘resolution’ of the violin plot.
ylim (tuple, (default: [None, None])) –
- Limit the width of the y-axis [min, max].
[None, None] : The width is determined based on the min-max value range.
title (String, (default: None)) –
- Title of the figure.
’Violin Chart’
filepath (String, (Default: user temp directory)) –
- File path to save the output.
Temporarily path: ‘Violin.html’
Relative path: ‘./Violin.html’
Absolute path: ‘c://temp//Violin.html’
None: Return HTML content.
figsize (tuple) –
- Size of the figure in the browser, [width, height].
[None, None]: The width is auto-determined based on the #labels.
showfig (bool, (default: True)) –
True: Open browser-window.
False: Do not open browser-window.
overwrite (bool, (default: True)) –
True: Overwrite the html in the destination directory.
False: Do not overwrite destination file but show warning instead.
notebook (bool) –
True: Use IPython to show chart in notebook.
False: Do not use IPython.
save_button (bool, (default: True)) –
True: Save button is shown in the HTML to save the image in svg.
False: No save button is shown in the HTML.
reset_properties (bool, (default: True)) –
True: Reset the node_properties at each run.
False: Use the d3.node_properties()
- Returns:
d3.node_properties – Contains properties of the unique input label/nodes/samples.
- Return type:
DataFrame of dictionary
- d3.edge_properties: DataFrame of dictionary
Contains properties of the unique input edges/links.
- d3.config: dictionary
Contains configuration properties.
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize >>> d3 = D3Blocks() >>> # >>> # Import example dataset >>> df = d3.import_example('cancer') >>> # >>> # Set some input variables. >>> tooltip = df['labx'].values + ' <br /> Survival: ' + df['survival_months'].astype(str).values >>> fontsize = df['age'].values >>> # fontsize = 16 # Set one fontsize for all nodes >>> # >>> # Create the chart >>> d3.violin(x=df['labx'].values, y=df['age'].values, fontsize=fontsize, tooltip=tooltip, bins=50, size=df['survival_months'].values/10, x_order=['acc','kich', 'brca','lgg','blca','coad','ov'], filepath='violine.html', figsize=[900, None]) >>> #
Examples
>>> # Load d3blocks >>> from d3blocks import D3Blocks >>> # >>> # Initialize for the Violin chart and set output to Frame. >>> d3 = D3Blocks(chart='Violin', frame=True) >>> # >>> # Import example dataset >>> df = d3.import_example('cancer') >>> # >>> # Set the properties by providing the labels >>> d3.set_edge_properties(x=df['labx'].values, y=df['age'].values, size=df['survival_months'].values/10, x_order=['acc','kich', 'brca','lgg','blca','coad','ov']) >>> # >>> # Set specific node properties. >>> d3.edge_properties.loc[0,'size']=50 >>> d3.edge_properties.loc[0,'color']='#000000' >>> d3.edge_properties.loc[0,'tooltip']='I am adjusted!' >>> d3.edge_properties.loc[0,'fontsize']=30 >>> # >>> # Configuration can be changed too. >>> print(d3.config) >>> # >>> # Show the chart >>> d3.show()
References
- d3blocks.d3blocks.disable_tqdm()
Set the logger for verbosity messages.
- d3blocks.d3blocks.get_logger()
Get logger status.
- d3blocks.d3blocks.random_date(start, end, prop, dt_format='%d-%m-%Y %H:%M:%S', strftime=True)
Create random dateTimes.
- d3blocks.d3blocks.set_chart_func(chart=None, logger=None)
Library compatibility checks.
- Return type:
chart function as Object.
- d3blocks.d3blocks.set_logger(verbose: [<class 'str'>, <class 'int'>] = 'info')
Set the logger for verbosity messages.
- Parameters:
verbose ([str, int], default is 'info' or 20) –
- Set the verbose messages using string or integer values.
0, 60, None, ‘silent’, ‘off’, ‘no’]: No message.
10, ‘debug’: Messages from debug level and higher.
20, ‘info’: Messages from info level and higher.
30, ‘warning’: Messages from warning level and higher.
50, ‘critical’: Messages from critical level and higher.
- Return type:
None.
Examples
>>> # Set the logger to warning >>> set_logger(verbose='warning') >>> >>> # Test with different messages >>> logger.debug("Hello debug") >>> logger.info("Hello info") >>> logger.warning("Hello warning") >>> logger.critical("Hello critical") >>>
- d3blocks.d3blocks.str_time_prop(start, end, prop, dt_format='%d-%m-%Y %H:%M:%S', strftime=True)
Get a time at a proportion of a range of two formatted times.
start and end should be strings specifying times formatted in the given format (strftime-style), giving an interval [start, end]. prop specifies how a proportion of the interval to be taken after start. The returned time will be in the specified format.
- d3blocks.d3blocks.unzip(path_to_zip, ext='')
Unzip files.
- Parameters:
path_to_zip (str) – Path of the zip file.
- Returns:
getpath – Path containing the unzipped files.
- Return type:
str
- d3blocks.d3blocks.wget(url, writepath)
Retrieve file from url.
- Parameters:
url (str.) – Internet source.
writepath (str.) – Directory to write the file.
- Return type:
None.