g2绘制双折线图+柱形图+自定义legend
程序员文章站
2022-04-21 21:39:20
...
这里绘制的柱形图是由双折线图的差值获得的,下面的代码可直接复制。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>柱状-折线(柱形的数据由折线差值得到)</title>
</head>
<body>
<div id="container"></div>
<script>
/*Fixing iframe window.innerHeight 0 issue in Safari*/ document.body
.clientHeight
</script>
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g2-3.5.1/dist/g2.min.js"></script>
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.data-set-0.10.1/dist/data-set.min.js"></script>
<script>
const data1 = [
{
month: '12/07',
type: '货币需求',
value: 45
},
{
month: '13/07',
type: '货币需求',
value: 39
},
{
month: '14/07',
type: '货币需求',
value: 40
}
]
const data2 = [
{
month: '12/07',
type: '货币供给',
value: 33
},
{
month: '13/07',
type: '货币供给',
value: 53
},
{
month: '14/07',
type: '货币供给',
value: 32
}
]
//折线差的数组
const gaps = []
//当前所有数字的数组
const nums = []
const data3 = data1.map((item, index) => {
const gap = item.value - data2[index].value
gaps.push(gap)
nums.push(item.value)
nums.push(data2[index].value)
return {
month: item.month,
value: gap,
type: '货币缺口'
}
})
const data4 = [...data1, ...data2]
console.log(data4, data3)
const chart = new G2.Chart({
container: 'container',
width: 300,
height: 180,
padding: 'auto'
})
chart.scale('value', {
min: Math.min(...gaps) - 1,
max: Math.max(...nums) + 1
})
const view3 = chart.view()
view3.source(data3)
view3
.interval()
.position('month*value')
.color('month', ['l(270) 0:#007bc7 1:#00dffd']) //柱形图渐变
const view4 = chart.view()
view4.source(data4)
view4
.line()
.position('month*value')
.color('type', ['#FFA900', '#FE5264'])
.shape('smooth')
view4.axis('month', false)
view4.axis('value', false)
//自定义legend
chart.legend({
custom: true,
clickable: false,
textStyle: {
fill: '#9bb7ef'
},
items: [
{
value: '货币缺口',
marker: {
symbol: 'square',
fill: '#3bf',
radius: 5,
lineWidth: 5
}
},
{
value: '货币需求',
marker: {
symbol: 'hyphen',
fill: '#FFA900',
stroke: '#FFA900',
radius: 5
}
},
{
value: '货币供给',
marker: {
symbol: 'hyphen',
fill: '#FE5264',
stroke: '#FE5264',
radius: 5
}
}
]
})
chart.tooltip(false)
chart.render()
</script>
</body>
</html>
上一篇: ==总结