关于React+antv g2柱状图的那些事
技术栈:react+antv g2
渲染基础柱状图:
import React, { Component } from 'react'
import { Chart } from '@antv/g2';
export class BarChart extends Component {
componentDidMount() {
const data = [
{ time: '1951 年', value: 38 },
{ time: '1952 年', value: 52 },
{ time: '1956 年', value: 61 },
{ time: '1957 年', value: 145 },
{ time: '1958 年', value: 48 },
{ time: '1959 年', value: 38 },
{ time: '1960 年', value: 38 },
{ time: '1962 年', value: 38 },
];
const chart = new Chart({
container: 'barcharts',
autoFit: true,
height: 300,
padding: [20, 30, 30, 70]
});
chart.data(data);//加载数据
chart.scale('value', {
nice: true,
});
chart.tooltip({
showMarkers: false,
});
chart.interaction('active-region')
chart.interval().position('time*value');
chart.render();
}
render() {
return (
<div id='barcharts' ></div>
)
}
}
export default BarChart;
1、修改tooltip标题:
chart.scale('value', {
nice: true,
alias: '人数',
});
2、修改y轴标题:
chart.axis('value', {
subTickLine: null,
offsetX: -15,
title: {
offset: 45,
style: {
textAlign: 'center', // 文本对齐方向,可取值为: start middle end
fill: '#000', // 文本的颜色
fontSize: 14, // 文本大小
fontWeight: 'lighter',
}
}
});
3、修改x、y轴颜色:
chart.axis('time', {
subTickLine: null,
line:{
style:{
lineWidth:2,//线的粗细
stroke:'red',//颜色
}
}
});
chart.axis('value', {
subTickLine: null,
line:{
style:{
lineWidth:2,
stroke:'red'
}
}
});
4、修改x、y轴文字颜色(只举例x轴写法)
chart.axis('time', {
label: {
style: {
textAlign: 'center', // 文本对齐方向,可取值为: start middle end
fill: 'orange', // 文本的颜色
fontSize: 14, // 文本大小
},
},
});
5、修改x轴文字显示
默认情况下,x轴文字太多,会隐藏部分。有时候需求就是要全部显示,只能旋转一下来显示全部咯。
chart.axis('time', {
label: {
style: {
textAlign: 'center', // 文本对齐方向,可取值为: start middle end
fill: 'orange', // 文本的颜色
fontSize: 14, // 文本大小
},
autoRotate: true, // 是否自动旋转(只设置这个,会根据数据多少自动决定是否旋转标题)
rotate: 0.5,// 旋转角度(设置这个,就算数据很少也会被旋转)
offset:15, // label 的偏移量(设置了旋转角度,可能要调整这个数值来使页面好看)
},
});
6、修改柱状图样式
chart.interval().position('time*value')
.color('time-value',function (active) {
return '#17BE74' //修改柱子颜色
})
.style({
radius: [20, 20, 0, 0],//设置圆角
stroke:'orange',//描边颜色
lineWidth:2,//描边线粗细
});
7、柱状图上展示数字
chart.interval().position('time*value')
.label('value', {
style: {
fill: 'orange',
},
})
想展示更详细内容的参考 这里
最后我还有个问题,这个网格线样式(粗细、颜色等)如何设置呢?如下图:
写在最后:上面写的这些就是自己在做项目时候遇到的需求,简单的配置我就没写了,官网都有。把这些写出来是记录一下,方便自己查阅,也希望遇到相同问题的小伙伴能快速找到需要的代码。还有不足的或者有更好玩的配置,希望大家在评论区一起讨论哦。(ps:最后那个问题我真不知道咋整,希望有知道的小伙伴告诉我哈)