charts.py 16 KB

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