charts.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. """A module that defines the chart components in Recharts."""
  2. from __future__ import annotations
  3. from collections.abc import Sequence
  4. from typing import Any, ClassVar
  5. from reflex.components.component import Component
  6. from reflex.components.recharts.general import ResponsiveContainer
  7. from reflex.constants import EventTriggers
  8. from reflex.constants.colors import Color
  9. from reflex.event import EventHandler, no_args_event_spec
  10. from reflex.vars.base import Var
  11. from .recharts import (
  12. LiteralAnimationEasing,
  13. LiteralComposedChartBaseValue,
  14. LiteralLayout,
  15. LiteralStackOffset,
  16. LiteralSyncMethod,
  17. RechartsCharts,
  18. )
  19. class ChartBase(RechartsCharts):
  20. """A component that wraps a Recharts charts."""
  21. # The width of chart container. String or Integer
  22. width: Var[str | int] = Var.create("100%")
  23. # The height of chart container.
  24. height: Var[str | int] = Var.create("100%")
  25. # The customized event handler of click on the component in this chart
  26. on_click: EventHandler[no_args_event_spec]
  27. # The customized event handler of mouseenter on the component in this chart
  28. on_mouse_enter: EventHandler[no_args_event_spec]
  29. # The customized event handler of mousemove on the component in this chart
  30. on_mouse_move: EventHandler[no_args_event_spec]
  31. # The customized event handler of mouseleave on the component in this chart
  32. on_mouse_leave: EventHandler[no_args_event_spec]
  33. @staticmethod
  34. def _ensure_valid_dimension(name: str, value: Any) -> None:
  35. """Ensure that the value is an int type or str percentage.
  36. Unfortunately str Vars cannot be checked and are implicitly not allowed.
  37. Args:
  38. name: The name of the prop.
  39. value: The value to check.
  40. Raises:
  41. ValueError: If the value is not an int type or str percentage.
  42. """
  43. if value is None:
  44. return
  45. if isinstance(value, int):
  46. return
  47. if isinstance(value, str) and value.endswith("%"):
  48. return
  49. if isinstance(value, Var) and issubclass(value._var_type, int):
  50. return
  51. raise ValueError(
  52. f"Chart {name} must be specified as int pixels or percentage, not {value!r}. "
  53. "CSS unit dimensions are allowed on parent container."
  54. )
  55. @classmethod
  56. def create(cls, *children: Any, **props: Any) -> Component:
  57. """Create a chart component.
  58. Args:
  59. *children: The children of the chart component.
  60. **props: The properties of the chart component.
  61. Returns:
  62. The chart component wrapped in a responsive container.
  63. """
  64. width = props.pop("width", None)
  65. height = props.pop("height", None)
  66. cls._ensure_valid_dimension("width", width)
  67. cls._ensure_valid_dimension("height", height)
  68. # Ensure that the min_height and min_width are set to prevent the chart from collapsing.
  69. # We are using small values so that height and width can still be used over min_height and min_width.
  70. # Without this, sometimes the chart will not be visible. Causing confusion to the user.
  71. # With this, the user will see a small chart and can adjust the height and width and can figure out that the issue is with the size.
  72. min_height = props.pop("min_height", 10)
  73. min_width = props.pop("min_width", 10)
  74. return ResponsiveContainer.create(
  75. super().create(*children, **props),
  76. width=width if width is not None else "100%",
  77. height=height if height is not None else "100%",
  78. min_width=min_width,
  79. min_height=min_height,
  80. )
  81. class CategoricalChartBase(ChartBase):
  82. """A component that wraps a Categorical Recharts charts."""
  83. # The source data, in which each element is an object.
  84. data: Var[Sequence[dict[str, Any]]]
  85. # The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}.
  86. margin: Var[dict[str, Any]]
  87. # If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
  88. sync_id: Var[str]
  89. # When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function. Default: "index"
  90. sync_method: Var[LiteralSyncMethod]
  91. # The layout of area in the chart. 'horizontal' | 'vertical'. Default: "horizontal"
  92. layout: Var[LiteralLayout]
  93. # The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
  94. stack_offset: Var[LiteralStackOffset]
  95. class AreaChart(CategoricalChartBase):
  96. """An Area chart component in Recharts."""
  97. tag = "AreaChart"
  98. alias = "RechartsAreaChart"
  99. # The base value of area. Number | 'dataMin' | 'dataMax' | 'auto'. Default: "auto"
  100. base_value: Var[int | LiteralComposedChartBaseValue]
  101. # Valid children components
  102. _valid_children: ClassVar[list[str]] = [
  103. "XAxis",
  104. "YAxis",
  105. "ReferenceArea",
  106. "ReferenceDot",
  107. "ReferenceLine",
  108. "Brush",
  109. "CartesianGrid",
  110. "Legend",
  111. "GraphingTooltip",
  112. "Area",
  113. "Defs",
  114. ]
  115. class BarChart(CategoricalChartBase):
  116. """A Bar chart component in Recharts."""
  117. tag = "BarChart"
  118. alias = "RechartsBarChart"
  119. # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number. Default: "10%"
  120. bar_category_gap: Var[str | int]
  121. # The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number. Default: 4
  122. bar_gap: Var[str | int]
  123. # The width of all the bars in the chart. Number
  124. bar_size: Var[int]
  125. # The maximum width of all the bars in a horizontal BarChart, or maximum height in a vertical BarChart.
  126. max_bar_size: Var[int]
  127. # The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. Default: "none"
  128. stack_offset: Var[LiteralStackOffset]
  129. # If false set, stacked items will be rendered left to right. If true set, stacked items will be rendered right to left. (Render direction affects SVG layering, not x position.) Default: False
  130. reverse_stack_order: Var[bool]
  131. # Valid children components
  132. _valid_children: ClassVar[list[str]] = [
  133. "XAxis",
  134. "YAxis",
  135. "ReferenceArea",
  136. "ReferenceDot",
  137. "ReferenceLine",
  138. "Brush",
  139. "CartesianGrid",
  140. "Legend",
  141. "GraphingTooltip",
  142. "Bar",
  143. ]
  144. class LineChart(CategoricalChartBase):
  145. """A Line chart component in Recharts."""
  146. tag = "LineChart"
  147. alias = "RechartsLineChart"
  148. # Valid children components
  149. _valid_children: ClassVar[list[str]] = [
  150. "XAxis",
  151. "YAxis",
  152. "ReferenceArea",
  153. "ReferenceDot",
  154. "ReferenceLine",
  155. "Brush",
  156. "CartesianGrid",
  157. "Legend",
  158. "GraphingTooltip",
  159. "Line",
  160. ]
  161. class ComposedChart(CategoricalChartBase):
  162. """A Composed chart component in Recharts."""
  163. tag = "ComposedChart"
  164. alias = "RechartsComposedChart"
  165. # The base value of area. Number | 'dataMin' | 'dataMax' | 'auto'. Default: "auto"
  166. base_value: Var[int | LiteralComposedChartBaseValue]
  167. # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number. Default: "10%"
  168. bar_category_gap: Var[str | int]
  169. # The gap between two bars in the same category. Default: 4
  170. bar_gap: Var[int]
  171. # The width or height of each bar. If the barSize is not specified, the size of the bar will be calculated by the barCategoryGap, barGap and the quantity of bar groups.
  172. bar_size: Var[int]
  173. # If false set, stacked items will be rendered left to right. If true set, stacked items will be rendered right to left. (Render direction affects SVG layering, not x position). Default: False
  174. reverse_stack_order: Var[bool]
  175. # Valid children components
  176. _valid_children: ClassVar[list[str]] = [
  177. "XAxis",
  178. "YAxis",
  179. "ReferenceArea",
  180. "ReferenceDot",
  181. "ReferenceLine",
  182. "Brush",
  183. "CartesianGrid",
  184. "Legend",
  185. "GraphingTooltip",
  186. "Area",
  187. "Line",
  188. "Bar",
  189. ]
  190. class PieChart(ChartBase):
  191. """A Pie chart component in Recharts."""
  192. tag = "PieChart"
  193. alias = "RechartsPieChart"
  194. # The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}.
  195. margin: Var[dict[str, Any]]
  196. # Valid children components
  197. _valid_children: ClassVar[list[str]] = [
  198. "PolarAngleAxis",
  199. "PolarRadiusAxis",
  200. "PolarGrid",
  201. "Legend",
  202. "GraphingTooltip",
  203. "Pie",
  204. ]
  205. # The customized event handler of mousedown on the sectors in this group
  206. on_mouse_down: EventHandler[no_args_event_spec]
  207. # The customized event handler of mouseup on the sectors in this group
  208. on_mouse_up: EventHandler[no_args_event_spec]
  209. # The customized event handler of mouseover on the sectors in this group
  210. on_mouse_over: EventHandler[no_args_event_spec]
  211. # The customized event handler of mouseout on the sectors in this group
  212. on_mouse_out: EventHandler[no_args_event_spec]
  213. class RadarChart(ChartBase):
  214. """A Radar chart component in Recharts."""
  215. tag = "RadarChart"
  216. alias = "RechartsRadarChart"
  217. # The source data, in which each element is an object.
  218. data: Var[Sequence[dict[str, Any]]]
  219. # The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}. Default: {"top": 0, "right": 0, "left": 0, "bottom": 0}
  220. margin: Var[dict[str, Any]]
  221. # The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage. Default: "50%"
  222. cx: Var[int | str]
  223. # The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage. Default: "50%"
  224. cy: Var[int | str]
  225. # The angle of first radial direction line. Default: 90
  226. start_angle: Var[int]
  227. # The angle of last point in the circle which should be startAngle - 360 or startAngle + 360. We'll calculate the direction of chart by 'startAngle' and 'endAngle'. Default: -270
  228. end_angle: Var[int]
  229. # The inner radius of first circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: 0
  230. inner_radius: Var[int | str]
  231. # The outer radius of last circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: "80%"
  232. outer_radius: Var[int | str]
  233. # Valid children components
  234. _valid_children: ClassVar[list[str]] = [
  235. "PolarAngleAxis",
  236. "PolarRadiusAxis",
  237. "PolarGrid",
  238. "Legend",
  239. "GraphingTooltip",
  240. "Radar",
  241. ]
  242. def get_event_triggers(self) -> dict[str, Var | Any]:
  243. """Get the event triggers that pass the component's value to the handler.
  244. Returns:
  245. A dict mapping the event trigger to the var that is passed to the handler.
  246. """
  247. return {
  248. EventTriggers.ON_CLICK: no_args_event_spec,
  249. EventTriggers.ON_MOUSE_ENTER: no_args_event_spec,
  250. EventTriggers.ON_MOUSE_LEAVE: no_args_event_spec,
  251. }
  252. class RadialBarChart(ChartBase):
  253. """A RadialBar chart component in Recharts."""
  254. tag = "RadialBarChart"
  255. alias = "RechartsRadialBarChart"
  256. # The source data which each element is an object.
  257. data: Var[Sequence[dict[str, Any]]]
  258. # The sizes of whitespace around the chart. Default: {"top": 5, "right": 5, "left": 5 "bottom": 5}
  259. margin: Var[dict[str, Any]]
  260. # The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage. Default: "50%"
  261. cx: Var[int | str]
  262. # The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage. Default: "50%"
  263. cy: Var[int | str]
  264. # The angle of first radial direction line. Default: 0
  265. start_angle: Var[int]
  266. # The angle of last point in the circle which should be startAngle - 360 or startAngle + 360. We'll calculate the direction of chart by 'startAngle' and 'endAngle'. Default: 360
  267. end_angle: Var[int]
  268. # The inner radius of first circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: "30%"
  269. inner_radius: Var[int | str]
  270. # The outer radius of last circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: "100%"
  271. outer_radius: Var[int | str]
  272. # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number. Default: "10%"
  273. bar_category_gap: Var[int | str]
  274. # The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number. Default: 4
  275. bar_gap: Var[str]
  276. # The size of each bar. If the barSize is not specified, the size of bar will be calculated by the barCategoryGap, barGap and the quantity of bar groups.
  277. bar_size: Var[int]
  278. # Valid children components
  279. _valid_children: ClassVar[list[str]] = [
  280. "PolarAngleAxis",
  281. "PolarRadiusAxis",
  282. "PolarGrid",
  283. "Legend",
  284. "GraphingTooltip",
  285. "RadialBar",
  286. ]
  287. class ScatterChart(ChartBase):
  288. """A Scatter chart component in Recharts."""
  289. tag = "ScatterChart"
  290. alias = "RechartsScatterChart"
  291. # The sizes of whitespace around the chart. Default: {"top": 5, "right": 5, "bottom": 5, "left": 5}
  292. margin: Var[dict[str, Any]]
  293. # Valid children components
  294. _valid_children: ClassVar[list[str]] = [
  295. "XAxis",
  296. "YAxis",
  297. "ZAxis",
  298. "ReferenceArea",
  299. "ReferenceDot",
  300. "ReferenceLine",
  301. "Brush",
  302. "CartesianGrid",
  303. "Legend",
  304. "GraphingTooltip",
  305. "Scatter",
  306. ]
  307. def get_event_triggers(self) -> dict[str, Var | Any]:
  308. """Get the event triggers that pass the component's value to the handler.
  309. Returns:
  310. A dict mapping the event trigger to the var that is passed to the handler.
  311. """
  312. return {
  313. EventTriggers.ON_CLICK: no_args_event_spec,
  314. EventTriggers.ON_MOUSE_DOWN: no_args_event_spec,
  315. EventTriggers.ON_MOUSE_UP: no_args_event_spec,
  316. EventTriggers.ON_MOUSE_MOVE: no_args_event_spec,
  317. EventTriggers.ON_MOUSE_OVER: no_args_event_spec,
  318. EventTriggers.ON_MOUSE_OUT: no_args_event_spec,
  319. EventTriggers.ON_MOUSE_ENTER: no_args_event_spec,
  320. EventTriggers.ON_MOUSE_LEAVE: no_args_event_spec,
  321. }
  322. class FunnelChart(ChartBase):
  323. """A Funnel chart component in Recharts."""
  324. tag = "FunnelChart"
  325. alias = "RechartsFunnelChart"
  326. # The layout of bars in the chart. Default: "centric"
  327. layout: Var[str]
  328. # The sizes of whitespace around the chart. Default: {"top": 5, "right": 5, "bottom": 5, "left": 5}
  329. margin: Var[dict[str, Any]]
  330. # The stroke color of each bar. String | Object
  331. stroke: Var[str | Color]
  332. # Valid children components
  333. _valid_children: ClassVar[list[str]] = ["Legend", "GraphingTooltip", "Funnel"]
  334. class Treemap(RechartsCharts):
  335. """A Treemap chart component in Recharts."""
  336. tag = "Treemap"
  337. alias = "RechartsTreemap"
  338. # The width of chart container. String or Integer. Default: "100%"
  339. width: Var[str | int] = Var.create("100%")
  340. # The height of chart container. String or Integer. Default: "100%"
  341. height: Var[str | int] = Var.create("100%")
  342. # data of treemap. Array
  343. data: Var[Sequence[dict[str, Any]]]
  344. # The key of a group of data which should be unique in a treemap. String | Number. Default: "value"
  345. data_key: Var[str | int]
  346. # The key of each sector's name. String. Default: "name"
  347. name_key: Var[str]
  348. # The treemap will try to keep every single rectangle's aspect ratio near the aspectRatio given. Number
  349. aspect_ratio: Var[int]
  350. # If set false, animation of area will be disabled. Default: True
  351. is_animation_active: Var[bool]
  352. # Specifies when the animation should begin, the unit of this option is ms. Default: 0
  353. animation_begin: Var[int]
  354. # Specifies the duration of animation, the unit of this option is ms. Default: 1500
  355. animation_duration: Var[int]
  356. # The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'. Default: "ease"
  357. animation_easing: Var[LiteralAnimationEasing]
  358. # The customized event handler of animation start
  359. on_animation_start: EventHandler[no_args_event_spec]
  360. # The customized event handler of animation end
  361. on_animation_end: EventHandler[no_args_event_spec]
  362. @classmethod
  363. def create(cls, *children, **props) -> Component:
  364. """Create a chart component.
  365. Args:
  366. *children: The children of the chart component.
  367. **props: The properties of the chart component.
  368. Returns:
  369. The Treemap component wrapped in a responsive container.
  370. """
  371. return ResponsiveContainer.create(
  372. super().create(*children, **props),
  373. width=props.pop("width", "100%"),
  374. height=props.pop("height", "100%"),
  375. )
  376. area_chart = AreaChart.create
  377. bar_chart = BarChart.create
  378. line_chart = LineChart.create
  379. composed_chart = ComposedChart.create
  380. pie_chart = PieChart.create
  381. radar_chart = RadarChart.create
  382. radial_bar_chart = RadialBarChart.create
  383. scatter_chart = ScatterChart.create
  384. funnel_chart = FunnelChart.create
  385. treemap = Treemap.create