charts.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. ]
  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
  120. bar_category_gap: Var[Union[str, int]] = Var.create_safe("10%", _var_is_string=True) # type: ignore
  121. # The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number
  122. bar_gap: Var[Union[str, int]] = Var.create_safe(4) # type: ignore
  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.
  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.)
  130. reverse_stack_order: Var[bool]
  131. # Valid children components
  132. _valid_children: 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: 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'
  166. base_value: Var[Union[int, LiteralComposedChartBaseValue]]
  167. # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number
  168. bar_category_gap: Var[Union[str, int]] # type: ignore
  169. # The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number
  170. bar_gap: Var[Union[str, int]] # type: ignore
  171. # The width of all the bars in the chart. Number
  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.)
  174. reverse_stack_order: Var[bool]
  175. # Valid children components
  176. _valid_children: 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.
  195. margin: Var[Dict[str, Any]]
  196. # Valid children components
  197. _valid_children: List[str] = [
  198. "PolarAngleAxis",
  199. "PolarRadiusAxis",
  200. "PolarGrid",
  201. "Legend",
  202. "GraphingTooltip",
  203. "Pie",
  204. ]
  205. def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
  206. """Get the event triggers that pass the component's value to the handler.
  207. Returns:
  208. A dict mapping the event trigger to the var that is passed to the handler.
  209. """
  210. return {
  211. EventTriggers.ON_CLICK: lambda: [],
  212. EventTriggers.ON_MOUSE_ENTER: lambda: [],
  213. EventTriggers.ON_MOUSE_LEAVE: lambda: [],
  214. }
  215. class RadarChart(ChartBase):
  216. """A Radar chart component in Recharts."""
  217. tag = "RadarChart"
  218. alias = "RechartsRadarChart"
  219. # The source data, in which each element is an object.
  220. data: Var[List[Dict[str, Any]]]
  221. # The sizes of whitespace around the chart.
  222. margin: Var[Dict[str, Any]]
  223. # The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage
  224. cx: Var[Union[int, str]]
  225. # The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage
  226. cy: Var[Union[int, str]]
  227. # The angle of first radial direction line.
  228. start_angle: Var[int]
  229. # 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'.
  230. end_angle: Var[int]
  231. # 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
  232. inner_radius: Var[Union[int, str]]
  233. # 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
  234. outer_radius: Var[Union[int, str]]
  235. # Valid children components
  236. _valid_children: List[str] = [
  237. "PolarAngleAxis",
  238. "PolarRadiusAxis",
  239. "PolarGrid",
  240. "Legend",
  241. "GraphingTooltip",
  242. "Radar",
  243. ]
  244. def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
  245. """Get the event triggers that pass the component's value to the handler.
  246. Returns:
  247. A dict mapping the event trigger to the var that is passed to the handler.
  248. """
  249. return {
  250. EventTriggers.ON_CLICK: lambda: [],
  251. EventTriggers.ON_MOUSE_ENTER: lambda: [],
  252. EventTriggers.ON_MOUSE_LEAVE: lambda: [],
  253. }
  254. class RadialBarChart(ChartBase):
  255. """A RadialBar chart component in Recharts."""
  256. tag = "RadialBarChart"
  257. alias = "RechartsRadialBarChart"
  258. # The source data which each element is an object.
  259. data: Var[List[Dict[str, Any]]]
  260. # The sizes of whitespace around the chart.
  261. margin: Var[Dict[str, Any]]
  262. # The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage
  263. cx: Var[Union[int, str]]
  264. # The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage
  265. cy: Var[Union[int, str]]
  266. # The angle of first radial direction line.
  267. start_angle: Var[int]
  268. # 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'.
  269. end_angle: Var[int]
  270. # 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
  271. inner_radius: Var[Union[int, str]]
  272. # 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
  273. outer_radius: Var[Union[int, str]]
  274. # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number
  275. bar_category_gap: Var[Union[int, str]]
  276. # The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number
  277. bar_gap: Var[str]
  278. # 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.
  279. bar_size: Var[int]
  280. # Valid children components
  281. _valid_children: List[str] = [
  282. "PolarAngleAxis",
  283. "PolarRadiusAxis",
  284. "PolarGrid",
  285. "Legend",
  286. "GraphingTooltip",
  287. "RadialBar",
  288. ]
  289. def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
  290. """Get the event triggers that pass the component's value to the handler.
  291. Returns:
  292. A dict mapping the event trigger to the var that is passed to the handler.
  293. """
  294. return {
  295. EventTriggers.ON_CLICK: lambda: [],
  296. EventTriggers.ON_MOUSE_ENTER: lambda: [],
  297. EventTriggers.ON_MOUSE_LEAVE: lambda: [],
  298. }
  299. class ScatterChart(ChartBase):
  300. """A Scatter chart component in Recharts."""
  301. tag = "ScatterChart"
  302. alias = "RechartsScatterChart"
  303. # The sizes of whitespace around the chart.
  304. margin: Var[Dict[str, Any]]
  305. # Valid children components
  306. _valid_children: List[str] = [
  307. "XAxis",
  308. "YAxis",
  309. "ZAxis",
  310. "ReferenceArea",
  311. "ReferenceDot",
  312. "ReferenceLine",
  313. "Brush",
  314. "CartesianGrid",
  315. "Legend",
  316. "GraphingTooltip",
  317. "Scatter",
  318. ]
  319. def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
  320. """Get the event triggers that pass the component's value to the handler.
  321. Returns:
  322. A dict mapping the event trigger to the var that is passed to the handler.
  323. """
  324. return {
  325. EventTriggers.ON_CLICK: lambda: [],
  326. EventTriggers.ON_MOUSE_DOWN: lambda: [],
  327. EventTriggers.ON_MOUSE_UP: lambda: [],
  328. EventTriggers.ON_MOUSE_MOVE: lambda: [],
  329. EventTriggers.ON_MOUSE_OVER: lambda: [],
  330. EventTriggers.ON_MOUSE_OUT: lambda: [],
  331. EventTriggers.ON_MOUSE_ENTER: lambda: [],
  332. EventTriggers.ON_MOUSE_LEAVE: lambda: [],
  333. }
  334. class FunnelChart(ChartBase):
  335. """A Funnel chart component in Recharts."""
  336. tag = "FunnelChart"
  337. alias = "RechartsFunnelChart"
  338. # The layout of bars in the chart. centeric
  339. layout: Var[str]
  340. # The sizes of whitespace around the chart.
  341. margin: Var[Dict[str, Any]]
  342. # Valid children components
  343. _valid_children: List[str] = ["Legend", "GraphingTooltip", "Funnel"]
  344. class Treemap(RechartsCharts):
  345. """A Treemap chart component in Recharts."""
  346. tag = "Treemap"
  347. alias = "RechartsTreemap"
  348. # The width of chart container. String or Integer
  349. width: Var[Union[str, int]] = "100%" # type: ignore
  350. # The height of chart container.
  351. height: Var[Union[str, int]] = "100%" # type: ignore
  352. # data of treemap. Array
  353. data: Var[List[Dict[str, Any]]]
  354. # The key of a group of data which should be unique in a treemap. String | Number | Function
  355. data_key: Var[Union[str, int]]
  356. # The treemap will try to keep every single rectangle's aspect ratio near the aspectRatio given. Number
  357. aspect_ratio: Var[int]
  358. # If set false, animation of area will be disabled.
  359. is_animation_active: Var[bool]
  360. # Specifies when the animation should begin, the unit of this option is ms.
  361. animation_begin: Var[int]
  362. # Specifies the duration of animation, the unit of this option is ms.
  363. animation_duration: Var[int]
  364. # The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'
  365. animation_easing: Var[LiteralAnimationEasing]
  366. # The customized event handler of animation start
  367. on_animation_start: EventHandler[lambda: []]
  368. # The customized event handler of animation end
  369. on_animation_end: EventHandler[lambda: []]
  370. @classmethod
  371. def create(cls, *children, **props) -> Component:
  372. """Create a chart component.
  373. Args:
  374. *children: The children of the chart component.
  375. **props: The properties of the chart component.
  376. Returns:
  377. The Treemap component wrapped in a responsive container.
  378. """
  379. return ResponsiveContainer.create(
  380. super().create(*children, **props),
  381. width=props.pop("width", "100%"),
  382. height=props.pop("height", "100%"),
  383. )
  384. area_chart = AreaChart.create
  385. bar_chart = BarChart.create
  386. line_chart = LineChart.create
  387. composed_chart = ComposedChart.create
  388. pie_chart = PieChart.create
  389. radar_chart = RadarChart.create
  390. radial_bar_chart = RadialBarChart.create
  391. scatter_chart = ScatterChart.create
  392. funnel_chart = FunnelChart.create
  393. treemap = Treemap.create