charts.py 17 KB

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