问题描述
我有一个要求,我需要将 1,2 之间的值显示为一个组,将 2,3 之间的值显示为一个单独的组。我正在尝试自定义 x 轴,但它不起作用
在上图中,我需要显示条形 3 和 3.5 以及它们之间的最小间隙,同样地显示 4 和 4.5 条
这是我的代码
<ResponsiveContainer width="100%" height="100%">
<ComposedChart
width={500}
height={400}
data={data}
>
<Cartesiangrid horizontal={false} strokeDasharray="4 4" />
<XAxis scale="point" dataKey="label" />
<YAxis label={{ value: 'No.Of Employees',angle: -90,position: 'insideLeft' }} tick={false} />
<Tooltip />
<Bar dataKey="count" barSize={40} fill="#AAE5F9" />
<Line connectNulls={true} strokeWidth={3} dot={false} type="monotone" dataKey="count" stroke="#3080ED" />
</ComposedChart>
</ResponsiveContainer>
任何帮助将不胜感激
解决方法
我假设您的数据如下所示:
const data = [
{label: "0",count: 0},{label: "1",count: null},{label: "2",count: 1},{label: "3",{label: "3.5",{label: "4",count: 2},{label: "4.5",{label: "5",];
它们必须转换为以下形式:
const data = [
{label: "0",countA: 0,countB: null},countA: null,countA: 1,{label: "3-3.5",countB: 1},{label: "4-4.5",countA: 2,countB: 0},];
第一种方法
添加另一个 Bar 组件以显示组中的值。
export default function App() {
return (
// <ResponsiveContainer width="100%" height="100%">
<ComposedChart
width={500}
height={400}
data={data}
>
<CartesianGrid horizontal={false} strokeDasharray="4 4" />
<XAxis scale="point" dataKey="label" />
<YAxis label={{ value: 'No.Of Employees',angle: -90,position: 'insideLeft' }} tick={false} />
<Tooltip />
<Bar dataKey="countA" barSize={20} fill="#AAE5F9" />
<Bar dataKey="countB" barSize={20} fill="#79B473" />
<Line connectNulls={true} strokeWidth={3} dot={false} type="monotone" dataKey="countA" stroke="#3080ED" />
</ComposedChart>
// </ResponsiveContainer>
);
}
结果:
第二种方法
如果您希望组中的列无论组中有多少个元素都具有相同的宽度,那么您可以自己为组绘制矩形。
const getPath = (x,y,width,height,uv,pv) => {
const height1= pv?(height/uv)*pv:height;
return `M${x},${y}
v${height}
h${width}
v${-height1}
h${-width/2}
v${(height1-height)}
h${-width/2}
Z`;
};
const MultiBar: FunctionComponent = (props) => {
const { fill,x,countA,countB } = props;
return <path d={getPath(x,countB)} stroke="none" fill={fill} />;
};
export default function App() {
return (
<ComposedChart
width={500}
height={400}
data={data}
>
<CartesianGrid horizontal={false} strokeDasharray="4 4" />
<XAxis dataKey="label" />
<YAxis type="number" domain={[0,2]} label={{ value: 'No.Of Employees',position: 'insideLeft' }} tick={false} />
<Bar
dataKey="countA"
fill="#AAE5F9"
shape={<MultiBar />}
>
</Bar>
<Line connectNulls={true} strokeWidth={3} dot={false} type="monotone" dataKey="countA" stroke="#3080ED" />
</ComposedChart>
);
}
结果:
getPath
函数返回用于绘制图表每个条形的 SVG 元素的路径。如果需要,您可以在组中的条形之间添加笔划或留出间隙。
此外,您需要通过所有 countA
和 countB
值的最大值设置 Y 轴的域:
<YAxis type="number" domain={[0,2]} ... />