charts.py 16 KB

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