提问人:iamconfusion 提问时间:10/19/2023 更新时间:10/25/2023 访问量:152
是否可以将网格线添加到 MUI x-charts 条形图?
Is it possible to add grid lines to MUI x-charts Bar chart?
问:
我想使用 mui 条形图创建一个图表。
import { BarChart } from ‘@mui/x-charts/BarChart;
我特别希望只添加从 y 轴上自动建立的刻度线延伸的水平网格线,但认为如果将来用户为其他可用图表(例如)寻找类似的解决方案,了解是否可以添加垂直网格线也会很有帮助。我认为垂直网格线在折线图的情况下会有所帮助)。
我无法真正尝试任何事情,因为我不确定如何去做(我是反应和使用 MUI 组件的新手,所以仍在学习如何设置元素的样式)
答:
1赞
Houssem
10/25/2023
#1
此功能在 Github 上打开了一个问题:https://github.com/mui/mui-x/issues/10158
同时,您可以创建一个自定义样式的路径,并用于确定线条位置并使用d3-scale
path
例:
import * as React from 'react';
import { styled } from '@mui/material/styles';
import { ScaleLinear } from 'd3-scale';
import {
ResponsiveChartContainer,
LinePlot,
useDrawingArea,
useYScale,
useXScale,
} from '@mui/x-charts';
const x = Array.from({ length: 21 }, (_, index) => -1 + 0.2 * index);
const linear = x.map((v) => -1 + v);
const poly = x.map((v) => -1 + v ** 2 - v);
const StyledPath = styled('path')<{ color: 'primary' | 'secondary' }>(
({ theme, color }) => ({
fill: 'none',
stroke: theme.palette.text[color],
shapeRendering: 'crispEdges',
strokeWidth: 1,
pointerEvents: 'none',
}),
);
function CartesianAxis() {
// Get the drawing area bounding box
const { left, top, width, height } = useDrawingArea();
// Get the two scale
const yAxisScale = useYScale() as ScaleLinear<any, any>;
const xAxisScale = useXScale() as ScaleLinear<any, any>;
const yOrigin = yAxisScale(0);
const xOrigin = xAxisScale(0);
const xTicks = [-2, -1, 1, 2, 3];
const yTicks = [-2, -1, 1, 2, 3, 4, 5];
return (
<React.Fragment>
{yTicks.map((value) => (
<StyledPath
key={value}
d={`M ${left} ${yAxisScale(value)} l ${width} 0`}
color="secondary"
/>
))}
{xTicks.map((value) => (
<>
<h6>hhh</h6>
<StyledPath
key={value}
d={`M ${xAxisScale(value)} ${top} l 0 ${height}`}
color="secondary"
/>
</>
))}
<StyledPath d={`M ${left} ${yOrigin} l ${width} 0`} color="primary" />
<StyledPath d={`M ${xOrigin} ${top} l 0 ${height}`} color="primary" />
</React.Fragment>
);
}
export default function OriginDemo() {
return (
<ResponsiveChartContainer
margin={{ top: 5, left: 5, right: 5, bottom: 5 }}
height={300}
series={[
{
type: 'line',
data: linear,
},
{
type: 'line',
data: poly,
},
]}
xAxis={[{ data: x, scaleType: 'linear', min: -1, max: 3 }]}
yAxis={[{ min: -2, max: 5 }]}
>
<CartesianAxis />
<LinePlot />
</ResponsiveChartContainer>
);
}
不过,您可以使用您的图表组件(例如:)并将<BarChart/>
<BarChart>
<CartisianAxis/>
<BarChart/>
这是演示: https://codesandbox.io/s/tender-napier-3htnp6?file=/src/Demo.tsx:1333-1343
评论