使用Holoviews和Bokeh按指定顺序排列桑基图的源与目标
Fix Target Order in Holoviews Sankey Diagram
To enforce your desired Target order (DD → LC → NT → VU → EN → CE), use one of these straightforward solutions:
1. Convert Target to Ordered Categorical
This is the simplest approach. By making the Target column an ordered categorical, Holoviews will respect your specified sequence when arranging nodes.
import pandas as pd import holoviews as hv import colorcet as cc # Define your desired Target order target_order = ["DD", "LC", "NT", "VU", "EN", "CE"] # Convert Target column to ordered categorical type sorted_df0['Target'] = pd.Categorical(sorted_df0['Target'], categories=target_order, ordered=True) # Create Sankey diagram sankey2 = hv.Sankey(sorted_df0, kdims=["Source", "Target"], vdims=["Value"]) # Set color palette and diagram options color_palette = cc.glasbey_dark[:len(sorted_df0)] opts.defaults(opts.Sankey(edge_color=hv.Cycle(values=color_palette))) sankey2.opts( cmap="PuBuGn_r", label_position='outer', width=1000, height=700, title="AAAA" )
2. Explicitly Define Node Order
If the categorical method doesn’t work, directly specify the node_order in the Sankey options to force Target nodes into your desired sequence.
import holoviews as hv import colorcet as cc # Define desired Target order target_order = ["DD", "LC", "NT", "VU", "EN", "CE"] # Get unique Source nodes (preserves their original order from the dataset) source_nodes = sorted_df0['Source'].unique().tolist() # Combine Source nodes with Target nodes in your preferred order node_order = source_nodes + target_order # Create Sankey diagram sankey2 = hv.Sankey(sorted_df0, kdims=["Source", "Target"], vdims=["Value"]) # Set options including custom node order color_palette = cc.glasbey_dark[:len(sorted_df0)] opts.defaults(opts.Sankey(edge_color=hv.Cycle(values=color_palette))) sankey2.opts( cmap="PuBuGn_r", label_position='outer', width=1000, height=700, title="AAAA", node_order=node_order # Enforce the custom node sequence )
Key Notes:
- Remove
plt.tight_layout()from your code—it’s a Matplotlib function and unnecessary for Holoviews/Bokeh plots. - Ensure all Target values in your dataset are included in the
target_orderlist to avoid missing nodes.
内容的提问来源于stack exchange,提问作者Sajna v.h
相关产品推荐
相关产品推荐

