charts.py 17 KB

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