Interactive Sankey Diagrams with Plotly in Python
Interactive Sankey Diagrams with Plotly in Python
Data visualization is crucial for understanding complex relationships within datasets. Sankey diagrams excel at illustrating flows and proportions between different categories, making them ideal for visualizing things like energy transfer, financial transactions, or user journeys. This tutorial delves into creating interactive Sankey diagrams using Plotly in Python, offering a powerful tool for insightful data exploration.
Why Plotly for Sankey Diagrams?
- Interactivity: Hover over elements for detailed information, enhancing user engagement.
- Customization: Fine-tune the appearance, colors, labels, and other aspects to meet specific needs.
- Ease of Use: Plotly's Python library simplifies the creation process with its intuitive syntax.
- Shareability: Easily export and share diagrams in various formats, including interactive HTML files.
Getting Started
Requirements
- Python 3.x
- Plotly:
pip install plotly
- Pandas (optional, for data handling):
pip install pandas
Building Your First Sankey Diagram
```python import plotly.graph_objects as go source = [0, 1, 0, 2, 3, 3] # Indices of source nodes target = [2, 3, 3, 4, 4, 5] # Indices of target nodes value = [8, 4, 2, 8, 4, 2] # Values representing flow magnitude label = ['A', 'B', 'C', 'D', 'E', 'F'] # Labels for each node fig = go.Figure(data=[go.Sankey( node = dict( pad = 15, thickness = 20, line = dict(color = "black", width = 0.5), label = label, color = "blue" ), link = dict( source = source, # indices correspond to labels, eg A1, A2, A1, B1, ... target = target, value = value ))]) fig.update_layout(title_text="Basic Sankey Diagram", font_size=10) fig.show() ```Code Breakdown
- `import plotly.graph_objects as go`: Imports the necessary Plotly library.
- `source`, `target`, `value`: Define the flow between nodes. `source` and `target` lists contain node indices, and `value` lists the corresponding flow magnitudes.
- `label`: Provides labels for each node.
- `go.Sankey()`: Creates the Sankey diagram object. `node` and `link` dictionaries configure node and link properties, respectively.
- `fig.update_layout()`: Sets the title and font size of the diagram.
- `fig.show()`: Displays the interactive Sankey diagram.
Running the Code
- Save the code as a Python file (e.g., `sankey_diagram.py`).
- Open a terminal or command prompt.
- Navigate to the directory where you saved the file.
- Run the script using the command:
python sankey_diagram.py
Comments
Post a Comment