[英]Structuring data in Recharts
我有一些數據是嵌套的,看起來有點像這樣:
let testData = [
{
animalType: 'Bird',
data: [
{
animalName: 'Raven',
animalLength: 120,
},
{
animalName: 'Hawk',
animalLength: 95,
},
],
},
{
animalType: 'Fish',
data: [
{
animalName: 'Salmon',
animalLength: 105,
},
],
},
{
animalType: 'Mammal',
data: [
{
animalName: 'Dog',
animalLength: 120,
},
{
animalName: 'Cat',
animalLength: 150,
},
],
},
];
我正在嘗試使用此數據創建 Recharts 條形圖,但它不起作用。 這是我需要圖表的樣子:
所以每個條形應該是 animalLength(和 animalName),並且應該在 X 軸上按 animalType 分組。 我一直在嘗試這個的每一次迭代,但似乎雙重嵌套數據不允許它工作。 Recharts 沒有很多這樣的例子,所以我想不出一個好主意。 這個很接近,但 X 軸和 Y 軸的值來自同一個 object。
這是我目前使用的 BarChart 代碼。 任何幫助將非常感激。
<BarChart
width={1000}
height={500}
data={testData}
margin={{ top: 40, right: 40, left: 0, bottom: 5 }}>
<XAxis dataKey='animalType' />
<YAxis dataKey='animalLength' />
<CartesianGrid strokeDasharray='3 3' />
{testData.forEach((agency) => {
<Bar type='monotone' dataKey='animalName' />;
})}
</BarChart>
如果在每種動物類型中你有 1 或 2 個動物名稱,這樣的事情就可以完成......如果你有更多,你將需要調整
import { BarChart, Bar, Cell, XAxis, YAxis, ResponsiveContainer } from 'recharts'
let data = [
{
animalType: 'Bird',
animal1Name: 'Raven',
animal1Length: 120,
animal1Color: 'red',
animal2Name: 'Hawk',
animal2Length: 95,
animal2Color: 'red',
},
{
animalType: 'Fish',
animal1Name: 'Salmon',
animal1Length: 105,
animal1Color: 'blue',
},
{
animalType: 'Mammal',
animal1Name: 'Dog',
animal1Length: 120,
animal1Color: 'green',
animal2Name: 'Cat',
animal2Length: 150,
animal2Color: 'green',
},
]
const App = () => {
const renderBar = ({ x, y, width, height, animal2Name, fill }) => {
return (
<rect
fill={fill}
width={width}
height={height}
x={animal2Name ? x : x + 60}
y={y}
className="recharts-rectangle"
></rect>
)
}
return (
<div style={{ width: '1000px', height: '300px' }}>
<ResponsiveContainer width="100%" height="100%">
<BarChart
width={500}
height={300}
data={data}
margin={{
top: 20,
right: 30,
left: 20,
bottom: 5,
}}
>
<XAxis dataKey="animalType" />
<YAxis />
<Bar dataKey="animal1Length" shape={renderBar}>
{data.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.animal1Color} />
))}
</Bar>
<Bar dataKey="animal2Length">
{data.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.animal2Color} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
)
}
export default App
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.