简体   繁体   中英

React Recharts data with array

I have an array of data with the following structure:

0:
  date: '01-12-2020',
  data: Array(2)
    {name: "plants", count: 5}
    {name: "water", count: 2}
1:
  date: '02-12-2020',
  data: Array(2)
    {name: "plants", count: 1}
    {name: "water", count: 4}
...

I would like to show the dates on the x-axis and render a line for each `name' category. In this case two lines, one for plants and one for water.

Should I format this code or can I use this array directly in recharts? I'm creating the array myself in the backend so I can also format it there.

I've tried something like this but it is not working:

<ResponsiveContainer width="100%" height={200}>
                <LineChart data={data}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="x" />

                    <YAxis />
                    <Tooltip />
                    {data.map((item, i) => (
                        <Line
                            dataKey={data[0].data[0].count}
                            type="monotone"
                            stroke={colors[0]}
                            activeDot={{ r: 8 }}
                        />
                    ))}
                </LineChart>
            </ResponsiveContainer>

Your data needs to be formatted into this:

[{date: '01-12-2020', plants: 5 water: 4}]

you can do as following:

 let result = []; data.map(entry) => { let obj = {date: entry.date} entry.data.map((entry1) => { obj[entry1.name] = entry1.count; }); result.push(obj) })

and your chart as following (your dataKey on XAxis is false)

<ResponsiveContainer width="100%" height={200}>
                <LineChart data={data}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" />

                    <YAxis />
                    <Tooltip />
                    {data.data.map((item, i) => (
                        <Line
                            dataKey={item.name}
                            type="monotone"
                            stroke={colors[0]}
                            activeDot={{ r: 8 }}
                        />
                    ))}
                </LineChart>
            </ResponsiveContainer>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM