1
0

charts.py 18 KB

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