Note
Go to the end to download the full example code.
Sankey Plots¶
Sankey plots (often called Sankey diagrams) can be generated using the fig_sankey() function, which returns a Plotly Go Figure object.
The plot below was generated using a synthetic dataset for a hypothetical community of 1200 people who are hospitalised.
The dataset is given below as a table (but can also be loaded from the docs/sources/plot-gallery/examples/csv/sankey.csv file).
Source |
Target |
Value |
|---|---|---|
Community |
Hospitalised |
1200 |
Hospitalised |
ICU |
300 |
Hospitalised |
Ward |
900 |
ICU |
Death |
80 |
ICU |
Recovered |
220 |
Ward |
Recovered |
850 |
Ward |
Death |
50 |
Here are the Python steps you need to generate the plot using the fig_sankey() function:
43 import pandas as pd
44 from isaricanalytics.visualisation import fig_sankey
45
46 # Load the CSV
47 data = pd.read_csv("./csv/sankey.csv")
48
49 # Create the labels, nodes, flows/arrows and annotations
50 labels = pd.Series(pd.unique(data[["source", "target"]].values.ravel()))
51 nodes = pd.DataFrame({
52 "label": labels,
53 "customdata": labels.apply(lambda x: f"{x} (synthetic)")
54 })
55 label_to_idx = {label: i for i, label in enumerate(labels)}
56 arrows = pd.DataFrame({
57 "source": data["source"].map(label_to_idx),
58 "target": data["target"].map(label_to_idx),
59 "value": data["value"],
60 "customdata": data.apply(lambda r: f"{r['source']} → {r['target']}: {r['value']} cases", axis=1)
61 })
62 annotations = pd.DataFrame([{
63 "text": "Sankey plot of Synthetic Outbreak Patient Case Flow",
64 "x": 0.5,
65 "y": 1.08,
66 "xref": "paper",
67 "yref": "paper",
68 "showarrow": False,
69 "font": {"size": 14}
70 }])
71
72 fig = fig_sankey(
73 [nodes, arrows, annotations],
74 )
75 fig.update_layout(autosize=True)
76 fig
Note
Any dataframe or CSV column names, or dictionary field labels, in the example above that are not specific to the dataset must be as given, otherwise the function may throw an exception or return an incorrect figure.
The figure height and width parameters can be set using the height
and width parameters, but it may be more convenient to let Plotly handle
this using the figure layout autosize
parameter. Refer to the fig_sankey()
function docstring for more information.
Total running time of the script: (0 minutes 0.217 seconds)