-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Wrap Recharts Sankey chart #6708
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
harsh21234i
wants to merge
15
commits into
reflex-dev:main
Choose a base branch
from
harsh21234i:fix/wrap-recharts-sankey-6558
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
e94c110
Wrap Recharts Sankey chart
574f851
Tighten Sankey data typing
00fa111
Tighten Sankey chart wrapper props
cc9bd95
Add Sankey chart changelog fragment
47f21ad
Merge remote-tracking branch 'origin/main' into fix/wrap-recharts-san…
masenf 900ab4d
Enable proper custom sankey node and link renderers
masenf 6c9066d
reflex-components-recharts depends on reflex-base `use_hook_var` and …
masenf cb445be
Add changelog, tests, and docs for reflex_base.vars.special
claude ad5de4f
Fix Sankey payload typing and package build
7a9c158
Address Sankey renderer review feedback
6a09841
Address Sankey docs and namespace feedback
aa25c05
Address final Sankey review nits
bd6054f
Merge remote-tracking branch 'upstream/main' into fix/wrap-recharts-s…
a217435
Merge branch 'main' into fix/wrap-recharts-sankey-6558
harsh21234i d9af11f
Merge branch 'main' into fix/wrap-recharts-sankey-6558
harsh21234i File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,221 @@ | ||
| --- | ||
| components: | ||
| - rx.recharts.SankeyChart | ||
| title: Sankey Chart | ||
| meta_description: "Create Sankey charts in Python with Reflex. Build interactive Recharts Sankey diagrams to visualize weighted flows between stages, categories, or systems." | ||
| --- | ||
|
|
||
| # Sankey Chart | ||
|
|
||
| ```python exec | ||
| import random | ||
| from typing import Any | ||
|
|
||
| import reflex as rx | ||
| ``` | ||
|
|
||
| Sankey charts in Reflex are built on [Recharts](https://recharts.org/), a React charting library, and created in pure Python. A Sankey chart visualizes weighted flows between nodes, making it useful for showing movement through stages, resource allocation, user journeys, and other source-to-target relationships. | ||
|
|
||
| ## Simple Example | ||
|
|
||
| An `rx.recharts.sankey_chart()` takes a `data` dictionary with `nodes` and `links`. Links refer to nodes by zero-based index. | ||
|
|
||
| ```python demo graphing | ||
| sankey_data = { | ||
| "nodes": [ | ||
| {"name": "Website"}, | ||
| {"name": "Landing Page"}, | ||
| {"name": "Product Page"}, | ||
| {"name": "Checkout"}, | ||
| {"name": "Purchase"}, | ||
| ], | ||
| "links": [ | ||
| {"source": 0, "target": 1, "value": 1200}, | ||
| {"source": 1, "target": 2, "value": 900}, | ||
| {"source": 2, "target": 3, "value": 420}, | ||
| {"source": 3, "target": 4, "value": 260}, | ||
| ], | ||
| } | ||
|
|
||
|
|
||
| def sankey_simple(): | ||
| return rx.recharts.sankey_chart( | ||
| rx.recharts.graphing_tooltip(), | ||
| data=sankey_data, | ||
| node_padding=24, | ||
| node_width=12, | ||
| link_curvature=0.55, | ||
| width="100%", | ||
| height=320, | ||
| ) | ||
| ``` | ||
|
|
||
| ## Stateful Example | ||
|
|
||
| Chart data can be tied to a State var. This example randomizes the flow values when the button is clicked. | ||
|
|
||
| ```python demo exec | ||
| class SankeyState(rx.State): | ||
| data: dict[str, Any] = { | ||
| "nodes": [ | ||
| {"name": "Marketing"}, | ||
| {"name": "Trial"}, | ||
| {"name": "Sales"}, | ||
| {"name": "Support"}, | ||
| {"name": "Retained"}, | ||
| ], | ||
| "links": [ | ||
| {"source": 0, "target": 1, "value": 600}, | ||
| {"source": 1, "target": 2, "value": 320}, | ||
| {"source": 2, "target": 4, "value": 210}, | ||
| {"source": 1, "target": 3, "value": 180}, | ||
| {"source": 3, "target": 4, "value": 130}, | ||
| ], | ||
| } | ||
|
|
||
| @rx.event | ||
| def randomize_flows(self): | ||
| for link in self.data["links"]: | ||
| link["value"] = random.randint(80, 700) | ||
|
|
||
|
|
||
| def sankey_stateful(): | ||
| return rx.vstack( | ||
| rx.recharts.sankey_chart( | ||
| rx.recharts.graphing_tooltip(), | ||
| data=SankeyState.data, | ||
| node={ | ||
| "fill": rx.color("accent", 7), | ||
| "stroke": rx.color("accent", 10), | ||
| "strokeWidth": 2, | ||
| }, | ||
| link={ | ||
| "stroke": rx.color("gray", 7), | ||
| "strokeOpacity": 0.35, | ||
| }, | ||
| node_padding=18, | ||
| node_width=14, | ||
| width="100%", | ||
| height=320, | ||
| ), | ||
| rx.button("Randomize flows", on_click=SankeyState.randomize_flows), | ||
| width="100%", | ||
| ) | ||
| ``` | ||
|
|
||
|
|
||
| ## Full Node / Link Customization | ||
|
|
||
| For complete control over node and link rendering, pass a | ||
| `@rx.recharts.sankey_chart.node` or `@rx.recharts.sankey_chart.link` decorated | ||
| function that returns an svg-based component. The function receives a | ||
| `Var[SankeyNodeProps]` or `Var[SankeyLinkProps]` object with the node or link | ||
| data `payload`, as well as the object's position and dimensions. You can use these | ||
| properties to construct a custom node or link. | ||
|
|
||
| Because the component renders inside the SVG element of the chart, you can only | ||
| use `rx.el.svg` components to construct the custom node or link. | ||
|
|
||
| The example below also uses `rx.recharts.use_chart_width()` to read the | ||
| rendered chart width and `rx.vars.use_id()` to generate a unique id that links | ||
| each link's gradient definition to the path that references it. | ||
|
|
||
| ```python demo graphing | ||
| styled_sankey_data = { | ||
| "nodes": [ | ||
| {"name": "Sources", "type": "source", "fill": rx.color("blue", 8)}, | ||
| {"name": "Direct", "type": "channel", "fill": rx.color("green", 8)}, | ||
| {"name": "Search", "type": "channel", "fill": rx.color("grass", 8)}, | ||
| {"name": "Paid", "type": "channel", "fill": rx.color("amber", 8)}, | ||
| {"name": "Revenue", "type": "outcome", "fill": rx.color("purple", 8)}, | ||
| ], | ||
| "links": [ | ||
| {"source": 0, "target": 1, "value": 350}, | ||
| {"source": 0, "target": 2, "value": 500}, | ||
| {"source": 0, "target": 3, "value": 220}, | ||
| {"source": 1, "target": 4, "value": 190}, | ||
| {"source": 2, "target": 4, "value": 260}, | ||
| {"source": 3, "target": 4, "value": 150}, | ||
| ], | ||
| } | ||
|
|
||
|
|
||
| def sankey_custom_render(): | ||
| @rx.recharts.sankey_chart.node | ||
| def custom_node( | ||
| node: rx.Var[rx.recharts.sankey_chart.SankeyNodeProps], | ||
| ) -> rx.Component: | ||
| # Determine if the node is at the right edge of the chart to adjust the label position accordingly. | ||
| is_out = node.x + node.width + 6 > rx.recharts.use_chart_width() | ||
| return rx.fragment( | ||
| rx.el.svg.text( | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| node.payload.name, | ||
| x=rx.cond(is_out, node.x - 6, node.x + node.width + 6), | ||
| y=node.y + node.height / 2, | ||
| text_anchor=rx.cond(is_out, "end", "start"), | ||
| fill=rx.color("gray", 12), | ||
| font_size=10, | ||
| ), | ||
| rx.el.svg.rect( | ||
| x=node.x, | ||
| y=node.y, | ||
| width=node.width, | ||
| height=node.height, | ||
| # Accessing custom keys in the payload needs a `dict` cast. | ||
| fill=node.payload.to(dict)["fill"], | ||
| stroke=rx.color("gray", 12), | ||
|
harsh21234i marked this conversation as resolved.
|
||
| stroke_width=1, | ||
| ), | ||
| ) | ||
|
|
||
| @rx.recharts.sankey_chart.link | ||
| def custom_link( | ||
| link: rx.Var[rx.recharts.sankey_chart.SankeyLinkProps], | ||
| ) -> rx.Component: | ||
| link_id = rx.vars.use_id() | ||
| source = link.payload.source.to(dict) | ||
| target = link.payload.target.to(dict) | ||
| return rx.fragment( | ||
| rx.el.svg.linear_gradient( | ||
| rx.el.svg.stop(offset="0%", stop_color=source["fill"]), | ||
| rx.el.svg.stop(offset="100%", stop_color=target["fill"]), | ||
| id=link_id, | ||
| ), | ||
| rx.el.svg.path( | ||
| d=( | ||
| f"M{link.sourceX},{link.sourceY} " | ||
| f"C{link.sourceControlX},{link.sourceY} " | ||
| f"{link.targetControlX},{link.targetY} " | ||
| f"{link.targetX},{link.targetY}" | ||
| ), | ||
| fill="none", | ||
| stroke=f"url(#{link_id})", | ||
| stroke_opacity=0.35, | ||
| stroke_width=link.linkWidth, | ||
| ), | ||
| rx.el.svg.text( | ||
| link.payload.value, | ||
| x=(link.sourceX + link.targetX) / 2, | ||
| y=(link.sourceY + link.targetY) / 2, | ||
| text_anchor="middle", | ||
| fill=rx.color("gray", 12), | ||
| font_size=10, | ||
| ), | ||
| ) | ||
|
|
||
| return rx.recharts.sankey_chart( | ||
| data=styled_sankey_data, | ||
| node=custom_node, | ||
| link=custom_link, | ||
| width="100%", | ||
| height=340, | ||
| ) | ||
| ``` | ||
|
|
||
| ## Related Charts | ||
|
|
||
| Explore more chart types you can build with Reflex and Recharts in pure Python: | ||
|
|
||
| - [Treemap](/docs/library/graphing/charts/treemap) | ||
| - [Funnel Chart](/docs/library/graphing/charts/funnelchart) | ||
| - [Pie Chart](/docs/library/graphing/charts/piechart) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Add `rx.vars.use_hook_var()` to create a `Var` bound to the value of a no-argument React hook imported from a given library, and `rx.vars.use_id()` to get React's stable `useId` value for the rendered component. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| """Special Vars for rendering values from the environment.""" | ||
|
|
||
| from types import UnionType | ||
| from typing import Any, TypeVar, cast, overload | ||
|
|
||
| from typing_extensions import TypeForm | ||
|
|
||
| from reflex_base.utils.imports import ImportVar | ||
| from reflex_base.utils.types import GenericType | ||
| from reflex_base.vars.base import Var, VarData, get_unique_variable_name | ||
|
|
||
| HOOK_VAR_TYPE = TypeVar("HOOK_VAR_TYPE") | ||
|
|
||
|
|
||
| @overload | ||
| def use_hook_var(library: str, hook: str) -> Var[Any]: ... | ||
|
|
||
|
|
||
| @overload | ||
| def use_hook_var( | ||
| library: str, hook: str, _var_type: TypeForm[HOOK_VAR_TYPE] | ||
| ) -> Var[HOOK_VAR_TYPE]: ... | ||
|
|
||
|
|
||
| @overload | ||
| def use_hook_var(library: str, hook: str, _var_type: UnionType) -> Var[Any]: ... | ||
|
|
||
|
|
||
| def use_hook_var(library: str, hook: str, _var_type: Any = Any) -> Var: | ||
| """Get a Var representing a React hook's value. | ||
|
|
||
| The value will depend on the context of the component in which it is used. | ||
|
|
||
| Args: | ||
| library: The library to import the hook from. | ||
| hook: The name of the hook. | ||
| _var_type: The type of the Var. | ||
|
|
||
| Returns: | ||
| A Var representing the React hook. | ||
| """ | ||
| var_name = get_unique_variable_name() | ||
| hook_alias = f"{hook}_{var_name}" | ||
| return Var( | ||
| var_name, | ||
| _var_type=cast(GenericType, _var_type), | ||
| _var_data=VarData( | ||
| imports={library: ImportVar(tag=hook, alias=hook_alias)}, | ||
| hooks=(f"const {var_name} = {hook_alias}();",), | ||
| ), | ||
| ).guess_type() | ||
|
|
||
|
|
||
| def use_id() -> Var[str]: | ||
| """Get the stable React useId hook value for a component. | ||
|
|
||
| Returns: | ||
| A Var representing the useId hook value. | ||
| """ | ||
| return use_hook_var(library="react", hook="useId", _var_type=str) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Added a Recharts Sankey chart wrapper (`rx.recharts.sankey_chart`) with support for custom node and link renderers, and `rx.recharts.use_chart_width()` for reading the rendered chart width as a `Var`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.