Skip to content

Commit

Permalink
fix for sankey fontsize
Browse files Browse the repository at this point in the history
  • Loading branch information
erdogant committed Dec 11, 2023
1 parent b042bb2 commit 582f7c2
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 10 deletions.
10 changes: 8 additions & 2 deletions d3blocks/d3blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,13 +982,17 @@ def sankey(self,
* '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.
Fontsize of the text: default: 10
fontsize: int or dict.
* 10 : All nodes get this fontsize
* {'Nuclear': 10, 'Wind': 20}
margin : dict.
margin, in pixels.
* "top" : 5
Expand Down Expand Up @@ -2825,6 +2829,8 @@ def set_node_properties(self, *args, **kwargs):
"""
# Make dict with properties
if self.config['chart']=='Sankey' and hasattr(self, 'config') and kwargs.get('fontsize', None) is None:
kwargs['fontsize'] = self.config['fontsize']
if self.chart is not None:
labels = self.chart.set_node_properties(*args, **kwargs)
else:
Expand Down
58 changes: 58 additions & 0 deletions d3blocks/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,64 @@
import pandas as pd
import numpy as np

# %%
from d3blocks import D3Blocks
d3 = D3Blocks()

# Sankey
sankey_table = d3.import_example(data='energy')
# Sort the Sankey table by 'source'
sankey_table.sort_values(by='source', inplace=True)

# Create a D3Blocks Sankey chart
d3 = D3Blocks(chart='Sankey', frame=True)
d3.config['figsize'] = [1200, 800]
d3.config['fontsize'] = 10

# Node properties
sankey_table['source'] = sankey_table['source'].astype(str)
sankey_table['target'] = sankey_table['target'].astype(str)
sankey_table['weight'] = sankey_table['weight'].astype(str)
d3.set_node_properties(sankey_table)

# Edge properties
d3.set_edge_properties(sankey_table, color='target', opacity='target')
d3.show()

# %%

# Initialize
from d3blocks import D3Blocks
# Sankey chart
d3 = D3Blocks(chart='Sankey', frame=True)
# Get example data
df = d3.import_example(data='energy')
# Create chart
html = d3.sankey(df,
fontsize=20,
color={'Nuclear': '#FF0000',
'Wind':'#FF0000',
'Electricity grid':'#7FFFD4',
'Bio-conversion':'#000000',
'Industry': '#000000'},
filepath=r'c:/temp/sankey.html'
)


# %%
from d3blocks import D3Blocks
d3 = D3Blocks()

# Sankey
df = d3.import_example(data='energy')
html = d3.sankey(df, fontsize=20)

d3.node_properties

# %%



# %% issue 45
# https://github.com/d3blocks/d3blocks/issues/45
# from d3blocks import D3Blocks
Expand Down
27 changes: 21 additions & 6 deletions d3blocks/sankey/Sankey.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ def set_config(config={}, link={}, node={}, margin={}, **kwargs):
config['showfig'] = kwargs.get('showfig', True)
config['overwrite'] = kwargs.get('overwrite', True)
config['cmap'] = kwargs.get('cmap', 'Set1')
config['fontsize'] = kwargs.get('fontsize', 10)
config['reset_properties'] = kwargs.get('reset_properties', True)
config['link'] = {**{"color": "source-target", "stroke_opacity": 0.5, "color_static": '#d3d3d3'}, **link}
config['node'] = {**{"align": "justify", "width": 15, "padding": 15, "color": "currentColor", 'fontsize': config['fontsize']}, **node}
config['node'] = {**{"align": "justify", "width": 15, "padding": 15, "color": "currentColor"}, **node}
config['margin'] = {**{"top": 5, "right": 1, "bottom": 5, "left": 1}, **margin}
config['notebook'] = kwargs.get('notebook', False)
config['save_button'] = kwargs.get('save_button', True)
config['fontsize'] = kwargs.get('fontsize', 10)
# return
return config

Expand Down Expand Up @@ -120,14 +120,26 @@ def set_node_properties(df, **kwargs):
for key in keys:
color[labels.get(key)] = color.pop(key)

# Get fontsize
# fontsize = df.get('fontsize', None)
# if fontsize is None: fontsize = kwargs.get('fontsize', None)
# if (fontsize is not None) and (not isinstance(fontsize, int)):
# # Make same changes in the labels for the input nodes
# labels = dict(zip(dfO['source'].values.tolist() + dfO['target'].values.tolist(), df['source'].values.tolist() + df['target'].values.tolist()))
# keys = list(fontsize.keys())
# for key in keys:
# fontsize[labels.get(key)] = fontsize.pop(key)
fontsize = kwargs.get('fontsize', 10)

# Store in final dict
dict_labels = {}
for i, label in enumerate(uilabels):
getcolor = '#d3d3d3'
# Change color if user-defined.
if color is not None:
getcolor = color.get(label, getcolor)
if color is not None: getcolor = color.get(label, getcolor)
# getfontsize = fontsize.get(label, getfontsize)
# create dict labels
dict_labels[label] = {'id': i, 'label': label, 'color': getcolor, 'fontsize': kwargs['node']['fontsize']}
dict_labels[label] = {'id': i, 'label': label, 'color': getcolor, 'fontsize': fontsize}
# Return
return dict_labels

Expand Down Expand Up @@ -173,6 +185,9 @@ def show(df, **kwargs):
config['align_select'] = {'left': '', 'right': '', 'justify': '', 'center': ''}
config['align_select'][config['node']['align']] = 'selected="selected"'

# Update the fontsize
config['fontsize'] = kwargs['node_properties']['fontsize'][0]

# Create the data from the input of javascript
X = get_data_ready_for_d3(df, node_properties)
# Check whether dataframe is circular
Expand Down Expand Up @@ -231,7 +246,7 @@ def write_html(X, config, custom_colors, logger=None):
'node_width': config['node']['width'],
'node_padding': config['node']['padding'],
'node_stroke_color': config['node']['color'],
'fontsize': config['fontsize'],
'font_size': config['fontsize'],

'SAVE_TO_SVG_SCRIPT': save_script,
'SAVE_BUTTON_START': show_save_button[0],
Expand Down
20 changes: 18 additions & 2 deletions d3blocks/sankey/d3js/sankey.js
Original file line number Diff line number Diff line change
Expand Up @@ -2201,6 +2201,15 @@
.attr("height", d => d.y1 - d.y0)
.attr("width", d => d.x1 - d.x0);

// CREATE DICT WITH THE LABEL AND FONTSIZE
/*
let font_size = {};
data.nodes.forEach(item => {
font_size[item.name] = item.fontsize;
});
*/
// console.log(font_size)

// SET THE NODE COLORS
let node_color = {};
data.nodes.forEach(item => {
Expand Down Expand Up @@ -2248,10 +2257,17 @@
.attr("stroke-width", ({width}) => Math.max(1, width))
.call(Lt ? path => path.append("title").text(({index: i}) => Lt[i]) : () => {
});


// console.log(font_size)
if (Tl) svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", {{ fontsize }})
.attr("font-size", {{ font_size }})
//.attr("font-size", (d, i) => data.nodes[i].fontsize)
//.attr("font-size", (d, i) => {
// console.log(data.nodes[i].fontsize);
// return data.nodes[i].fontsize;
//})
// .attr("font-size", (d, i) => font_size[G[i]])
.selectAll("text")
.data(nodes)
.join("text")
Expand Down

0 comments on commit 582f7c2

Please sign in to comment.