G2是蚂蚁金服研发的,一套面向常规统计图表,以数据驱动的高交互可视化图形语法,具有高度的易用性和扩展性。使用 G2,你可以无需关注图表各种繁琐的实现细节,一条语句即可使用 Canvas 或 SVG 构建出各种各样的可交互的统计图表。可以查看官网例子以及文档说明。
此例子是为实现同一条曲线不同颜色显示。
1、利用渐进色实现
代码实现如下
<html>
<head>
<meta charset="utf-8">
<title>Line坐标轴属性</title>
<!-- 引入 g2.min.js -->
<script src="./g2/dist/g2.min.js"></script>
<style type="text/css">
html,body{
height:100%;
}
</style>
</head>
<body>
<h4>Line坐标轴设置</h4>
<!--建立图表容器-->
<div id="c1"></div>
<script>
const data = [
{ genre: 'Sports', sold: 275,phone:"iPhone" },
{ genre: 'Strategy', sold: 115 ,phone:"iPhone"},
{ genre: 'Action', sold: 120 ,phone:"xiaoni"},
{ genre: 'Shooter', sold: 350 ,phone:"lx"},
{ genre: 'Other', sold: 150 ,phone:"huawei"},
];
// Step 1: 创建 Chart 对象
const chart = new G2.Chart({
container: 'c1', // 指定图表容器 ID
width: 600, // 指定图表宽度
height: 300, // 指定图表高度
});
//y轴修改坐标轴线上的内容(利用scale的alias实现)
chart.scale('sold', {
alias: '销售量',
nice: true,
formatter: val => `${val}个`,
});
chart.axis('sold', {
title: {
style: {
fill: '#1890ff',
fontSize:20,
},
},
});
//设置x标轴
chart.axis("genre",{
label: //标签设置
{
formatter: (text) => {
return text+"$";
},
},
title:{
style: {
fill: '#1890ff',
},
}
});
//绘制点,与下面曲线配合
chart.point()
.position('genre*sold')
.color('#ff0000')
.shape('circle');
// Step 3:创建图形语法,绘制曲线
//chart.legend('sold', false);
chart.line()
.position('genre*sold')
.shape('smooth') //圆滑曲线,默认是折线
.color("l(90) 0:#ff0000 0.5:#7ec2f3 1:#ff0000") //颜色设置,采用渐变的实现
;
// Step 2: 载入数据源
chart.data(data);
// Step 4: 渲染图表
chart.render();
</script>
</body>
</html>
2.利用annotation().regionFilter实现
代码如下(来自于官网例子)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>RegionFilter</title>
</head>
<body>
<div id="container" />
<script src="./g2/dist/g2.min.js"></script>
<script>
fetch('https:/g2.antv.vision/zh/examples/data/tempChange.json')
.then(res => res.json())
.then(data => {
const chart = new G2.Chart({
container: 'container',
autoFit: true,
height: 500
});
chart.data(data);
chart.area().position('year*change').color('white')
.shape('smooth');
chart.line().position('year*change').color('green')
.shape('smooth');
chart.annotation().regionFilter({
top: true,
start: ['min', 0],
end: ['max', 'min'],
color: '#FFFF00'
});
chart.annotation().regionFilter({
top: true,
start: ['min', 'max'],
end: ['max', 0],
color: '#FF4D4F'
});
chart.render();
});
</script>
</body>
</html>