多个图表

1import { AreaChart, Chart, LineChart, Navigation, NavigationStack, RoundedRectangle, RuleLineForLabelChart, Script, Text, useMemo, useState, VStack, ZStack } from "scripting"
2
3const data = [
4  { sales: 1200, year: '2020', growth: 0.14, },
5  { sales: 1400, year: '2021', growth: 0.16, },
6  { sales: 2000, year: '2022', growth: 0.42, },
7  { sales: 2500, year: '2023', growth: 0.25, },
8  { sales: 3600, year: '2024', growth: 0.44, },
9]
10
11function Example() {
12  const [chartSelection, setChartSelection] = useState<string | null>()
13  const selectedItem = useMemo(() => {
14    if (chartSelection == null) {
15      return null
16    }
17    return data.find(item => item.year === chartSelection)
18  }, [chartSelection])
19
20  return <NavigationStack>
21    <VStack
22      navigationTitle={"Multiple Charts"}
23      navigationBarTitleDisplayMode={"inline"}
24    >
25      <Text>
26        Press and move on the chart to view the details.
27      </Text>
28      <Chart
29        frame={{
30          height: 300,
31        }}
32        chartXSelection={{
33          value: chartSelection,
34          onChanged: setChartSelection,
35          valueType: "string"
36        }}
37      >
38        <LineChart
39          marks={data.map(item => ({
40            label: item.year,
41            value: item.sales,
42            interpolationMethod: "catmullRom",
43            symbol: "circle",
44          }))}
45        />
46        <AreaChart
47          marks={data.map(item => ({
48            label: item.year,
49            value: item.sales,
50            interpolationMethod: "catmullRom",
51            foregroundStyle: ["rgba(255,100,0,1)", "rgba(255,100,0,0.2)"]
52          }))}
53        />
54        {selectedItem != null
55          ? <RuleLineForLabelChart
56            marks={[{
57              label: selectedItem.year,
58              foregroundStyle: { color: "gray", opacity: 0.5 },
59              annotation: {
60                position: "top",
61                overflowResolution: {
62                  x: "fit",
63                  y: "disabled"
64                },
65                content: <ZStack
66                  padding
67                  background={
68                    <RoundedRectangle
69                      cornerRadius={4}
70                      fill={"regularMaterial"}
71                    />
72                  }
73                >
74                  <Text
75                    foregroundStyle={"white"}
76                  >Sales: {selectedItem.sales}</Text>
77                </ZStack>
78              }
79            }]}
80          />
81          : null}
82      </Chart>
83    </VStack>
84  </NavigationStack>
85}
86
87async function run() {
88  await Navigation.present({
89    element: <Example />
90  })
91
92  Script.exit()
93}
94
95run()