如何移除Victory Chart粉色坐标轴左侧的蓝色网格线

问题说明
使用Victory Charts开发图表时,需要移除粉色坐标轴左侧的蓝色网格线,仅保留粉色坐标轴右侧的网格线,查阅VictoryAxis官方文档后未找到对应配置项可直接实现该需求。
当前编写的代码如下:
<VictoryAxis offsetX={55} verticalAnchor={'start'} name={'vertical-axis-1'} style={{ axis: { stroke: 'pink' }, grid: { stroke: 'blue', strokeDasharray: '6, 2', strokeWidth: 1 }, }} dependentAxis={true} crossAxis={true} tickValues={[22, 30, 37, 45, 52]} />
实现方案
Victory没有内置单侧网格线的开关配置,通过自定义网格组件加SVG裁剪就能实现效果,操作很简单:
- 自定义网格线组件,给网格线加裁剪规则,只渲染坐标轴x坐标右侧的线段
- 在VictoryAxis上通过
gridComponent属性指定这个自定义组件替换默认网格线
修改后的可直接运行的代码示例:
import { VictoryAxis, Line } from 'victory'; // Web端直接用原生svg标签即可,React Native端从react-native-svg引入ClipPath、Rect const SingleSideGrid = (props) => { const axisPositionX = props.x; const clipPathId = `right-side-grid-${props.name}`; return ( <> <defs> <clipPath id={clipPathId}> {/* 裁剪区域从坐标轴位置开始,覆盖整个右侧画布,宽高按自己项目的画布尺寸调整即可 */} <rect x={axisPositionX} y={0} width="2000" height="2000" /> </clipPath> </defs> <Line {...props} clipPath={`url(#${clipPathId})`} /> </> ); }; // 修改原VictoryAxis配置,增加gridComponent属性 <VictoryAxis offsetX={55} verticalAnchor={'start'} name={'vertical-axis-1'} gridComponent={<SingleSideGrid />} style={{ axis: { stroke: 'pink' }, grid: { stroke: 'blue', strokeDasharray: '6, 2', strokeWidth: 1 }, }} dependentAxis={true} crossAxis={true} tickValues={[22, 30, 37, 45, 52]} />
如果你的坐标轴位置是固定死的,也可以直接给grid样式加x1属性固定网格线起点在坐标轴位置,不过上面的裁剪方案适配性更好,后续调整坐标轴偏移、画布尺寸都不需要改逻辑。
内容的提问来源于stack exchange,提问作者smolkitty
相关产品推荐
相关产品推荐

