const data = [
{ name: "Yes", value: 35 },
{ name: "Not sure", value: 21 },
{ name: "No", value: 13 },
];
<ResponsiveContainer
width={"100%"}
height={"100%"}
>
<BarChart
layout="horizontal"
data={data}
margin={{
top: 20,
right: 20,
bottom: 20,
left: 20,
}}
>
<XAxis dataKey={"name"} />
<YAxis dataKey="value" />
<Bar dataKey="value" fill="#413ea0" />
</BarChart>
</ResponsiveContainer>
但是,当更改布局和数据键值时,信息无法正确显示:
<ResponsiveContainer
width={"100%"}
height={"100%"}
>
<BarChart
layout="vertical"
data={data}
margin={{
top: 20,
right: 20,
bottom: 20,
left: 20,
}}
>
<XAxis dataKey={"value"} />
<YAxis dataKey="name" />
<Bar dataKey="value" fill="#413ea0" />
</BarChart>
</ResponsiveContainer>
我尝试阅读文档
recharts API 默认
XAxis
为 type="category"
,YAxis
为 type="number"
,因此当您交换默认布局时,您还需要交换哪个轴是哪种类型。
在这种情况下:
<XAxis type="number" />
<YAxis dataKey="name" type="category" />
这是一个沙箱,演示了您需要在两者之间切换的内容。
https://codesandbox.io/p/sandbox/simple-bar-chart-toggle-layout-tkjczm