-
2022-03-19 10:59:26
在html中使用G2Plot
1、引入G2Plot图表组件库
<script type="text/javascript" src="https://unpkg.com/@antv/g2plot@latest/dist/g2plot.min.js"></script>
2、创建图表容器
<div id="container"></div>
3、创建图表
<script>
3-1创建图表的构造函数
let Column = G2Plot.Column;
3-2创建图表的实例对象
let column = new Column('container', {
data: [ ],
xField: ' ',
yField: ' ',
});
4、渲染 render()
column.render();
</script>
在vue项目中使用G2Plot
1、引入G2Plot图表组件库
package.json中已全局引入,所以无需每次引入
2、创建图表容器
<div ref="box"></div>
3、创建图表
<script>
3-1创建图表的构造函数
import { Line } from "@antv/g2plot";
export default {
data() {},
methods: {
// 加载函数
loadLine() {
// 3-2创建图表的实例对象
let line = new Line(this.$refs["box"], {
data: [ ],
xField: " ",
yField: " ",
});
// 4、渲染 render()
line.render();
},
},
// 5、在生命周期中调用
mounted() {
this.loadLine();
},
};
</script>
用yarn安装依赖
在集成终端中打开
cnpm install yarn -global
yarn -v
yarn install
yarn serve或者npm run serve
项目打包
npm run build
生成dist文件,重命名为项目名称
上传到阿里云服务器
在filezilla中将重命名好的文件夹拖到/var/www/html中
在浏览器中访问
公网ip/文件夹名称(39.104.24.238/2019年临猗县政务分析监测中心)
更多相关内容 -
g2plot-react:用于React的G2Plot
2021-02-05 00:41:27@ opd / g2plot-react 用于React的 安装 npm install @opd/g2plot-react 用法 import React , { useRef } from 'react' import { LineChart , LineChartProps } from '@opd/g2plot-react' const config : ... -
快速上手AntV G2Plot
2021-01-08 12:38:49快速上手AntV G2Plot 小白一枚,引入官方示例各种报错,发现Line对象在G2Plot对象里面! 将const linePlot = new Line()…改为const linePlot = new G2Plot.Line后正常, 标题复制下面代码可直接出效果 /... -
雨果-g2plot
2021-02-10 20:48:39雨果-g2plot 关于 这不是一个独立的主题。 它是一个主题组件,提供了一个g2plot : g2plot以在您的Hugo网站中显示 。 用法 将hugo-g2plot添加为子模块,以便以后能够进行上游更改git submodule add ... -
g2plot-theme-builder::lipstick:为G2Plot构建主题配置:chart_increasing:
2021-04-04 12:46:14关于G2和G2Plot的在线主题生成器。 -
React+G2 + G2plot 踩坑
2022-02-10 15:02:18这里写自定义目录标题参与图表组件库开发(要求使用Echarts或G2)坑1: 参与图表组件库开发(要求使用Echarts或G2) 因为这两个都没用过,翻阅多篇文章,最终选择入坑G2,要用就用新技术!所以特此记录,方便以后避...参与图表组件库开发(要求使用Echarts或G2)
因为这两个都没用过,翻阅多篇文章,最终选择入坑G2,要用就用新技术!所以特此记录一些常用的,方便以后避坑。Echarts或G2对于我这样没用过的人来说API实在太多了没法记,所以我也不喜欢一点一点去看官方文档,更多是了解了基础原理直接看官网例子代码,不知道有人和我一样么?所以常用的我都会在下面代码注释中体现到底是干什么的。不会将某个属性展开说,什么包含那些等,遇到问题知道去找那个属性关键词就可以了
G2核心概念视觉通道
在 G2 中我们实现了如下类型的视觉通道(也称图形属性):、
- position(位置),二维坐标系内可以映射到 x,y,三维坐标系可以映射到 x,y,z。
- color(颜色),包含了色调、饱和度和亮度。
- size(大小),不同的图形对大小的定义有所差异。
- shape(形状),图形的形状决定了某个图表类型的表现方式。例如 点图,可以使用圆点、三角形、小 的图片表示;线图可以使用折线、曲线、点线等表现形式。
G2 图表组成
1.G2在react中的写法,看了各种写法,个人更加偏爱这种:
//写在useEffect当中我是觉得方便一些,但是有缺陷就是在外面找不到chart实例,没法对chart做操作 //所以有知道的大佬可以说一下一般标准的写法是怎么写的 useEffect(() => { const chart = new Chart({ container: container, autoFit: true, height: 500, }); ... chart.interval().position('type*value') ... chart.render(); },[ ])
2.示例图加注释:
a.圆形柱状图?(颜色随数据改变)
我做的:
要求的:
//图片中渐变边框我选择用css实现,G2应该也可以实现但是很麻烦 //可以理解为两个极坐标的柱状图,一深一浅重叠 const used=68; //使用率 假数据 let colors=['#D3EAFF', '#2495FF']; //颜色假数据 const data1: object[] = []; //深色假数据 for (let i = 0; i < 20; i++) { //控制柱状个数 data1.push({ type: i + '', value: 10, }); } let data2: object[]= []; //浅色假数据 for (let i = 0; i < 20; i++) { const item = { type: '', value: 1 }; item.type = i + ''; item.value = 10; let transused = used / 5; //100为满,20个柱子所以/5 转换 if (i >= transused) { item.value = 0; } data2.push(item);} const chart = new Chart({ //创建Chart实例 container: container, //容器id名称 autoFit: true, //是否随着屏幕自适应宽高 height: 500, //也可以单独设置宽高 }); chart.legend(false); //不显示图例 chart.tooltip(false); //不显示提示 就是鼠标滑过时的文字 const view1 = chart.createView(); //创建view实例,View 是图层容器的概念,和ps中图层差不多,重叠顺序,没有重叠的图直接用chart就行 view1.data(data1); //绑定数据源 view1.axis(false); //不显示坐标轴 view1.coordinate('polar', { //坐标类型:极坐标 innerRadius: 0.7, //极坐标内半径 radius: 100, //极坐标半径 innerRadius,radius,以及假数据的20个数,可以调整其比例达到自己想要的间隙或者柱子宽度 }); view1 .interval() //Geom几何标记类型,interval:使用矩形或者弧形,用面积来表示大小关系的图形,一般构成柱状图、饼图等图表。 //下面都是图形属性 .position('type*value') //坐标系映射 .color(String(used), (cValue) => { //颜色,支持字符串和这种写法,不接受变量,我试过了 if (Number(cValue) >= 90) { return '#FBDBD9'; } else if (Number(cValue) >= 70) { return '#FEF1DD'; } return colors[0]; }) // .color('value',String(colors[0])) .size(6); //大小 const view2 = chart.createView(); //图层二 同上 view2.data(data2); view2.axis(false); view2.coordinate('polar', { innerRadius: 0.7, radius: 100, }); view2 .interval() .position('type*value') // .color(String(colors[1])) .color(String(used), (cValue) => { if (Number(cValue) >= 90) { return '#EF5C52'; } else if (Number(cValue) >= 70) { return '#F8B755'; } return colors[1]; }) .size(6); chart.render(); //渲染 }, []);
b.柱状图(y轴分割线虚线,重叠,隔行显示文字)
const data = [ { type: 'this', info: '人脸搜索', value: 760 }, { type: 'this', info: '人体搜索', value: 520 }, { type: 'this', info: '机动车搜索', value: 820 }, { type: 'this', info: '非机动车搜索', value: 300 }, ]; let max = 0; //用来计算y坐标轴最高数值 data.forEach((item) => { if (item.value > max) { max = item.value; } }); let data1 = data.map((item) => { //阴影灰色柱状图 return { type: 'all', info: item.info, value: Math.ceil(max / 600) * 600 - item.value }; }); data.unshift(...data1); const chart = new Chart({ container: 'container', autoFit: true, }); chart.data(data); //导入数据 chart .interval() .position('info*value') .size(12) .label('value', (xValue) => { //显示文本内容 return { content: xValue + '次', }; }) .color('type', ['#EEEEEE', '#2495FF']) //重叠 .adjust('stack'); //设置数据调整方式,stack:层叠,第一个那个图表应该也可以用这个实现,稍微简单一点 chart.axis('value', { //坐标轴 title: null, // 不展示 xField 对应坐标轴的标题 label: { //隔行展示坐标轴文本 formatter: (val) => { // 使用 formatter 回调函数 if ((Number(val) / 300) % 2 !== 0) { return ''; } else { return val; } }, }, //网格虚线 grid: { line: { style: { stroke: '#d9d9d9', lineWidth: 1, lineDash: [2, 2], }, }, }, }); chart.scale('value', { //度量(Scale)用于定义数据的类型和展示方式 nice: true, //自动调整 min、max 。 tickInterval: 300, //控制间隔 }); //所有提示都不展示 chart.tooltip(false); //所有图例都不展示 chart.legend(false); //交互:鼠标在画布上移动是,对应的区域出现背景框 chart.interaction('active-region'); chart.render();
c.自定义图形柱状图(渐变,隔行换色,最大的感受G2文档太少了,不详细)
按照下面写法没法实现,我也不知道为什么,而且无法自适应了,奈何文档资料有限,百度都百度不到,没办法耗了半天天打算用Echarts重写…,但是G2写法也亮出来,请大家看看问题在哪里
G2:import { Chart,registerShape } from '@antv/g2'; registerShape('interval', 'triangle', { //注册自定义shape接口 getPoints(cfg:any) { // 定义关键点 const x = cfg.x; const y = cfg.y; const y0 = cfg.y0; const width = cfg.size; return [ { x: x - width / 2, y: y0 }, { x: x, y: y }, { x: x + width / 2, y: y0 }, ]; }, // 2. 绘制 draw(cfg, group) { const points = this.parsePoints(cfg.points); // 将0-1空间的坐标转换为画布坐标 //添加自定义shape ,实测其中image,dom类型,没法用,查不到为什么,官网也没有,那位大佬可以说一下为什么么?具体地址:https://g.antv.vision/zh/docs/api/canvas group.addShape('path', { //采用路径方式 attrs: { //这个路径就是< svg >< path d="............" >< /svg > d中的值 path:'M2.08269 86.5C28.1667 72.8126 45.3971 46.8239 48 17.6787C50.6029 46.8239 67.8333 72.8126 93.9173 86.5H2.08269Z', stroke:cfg.color, //线条颜色 lineWidth:2, //线条宽度 fill:cfg.color, //填充颜色 }, }); return group; }, }); const data = [ { type: 'this', info: '功能名称1', value: 1360 }, { type: 'this', info: '功能名称2', value: 1000 }, { type: 'this', info: '功能名称3', value: 980 }, { type: 'this', info: '功能名称4', value: 900 }, { type: 'this', info: '功能名称5', value: 860 }, ]; let max = 0; data.forEach((item) => { if (item.value > max) { max = item.value; } }); const chart = new Chart({ container: 'container', autoFit: true, }); chart.data(data); chart .interval() .position('info*value') .label('value', (xValue) => { return { content: xValue + '次', }; }) .size(100) .color('info',(cVal)=>{ let count=0; data.forEach((item,index)=>{ if(item.info===cVal){ count=index+1 } }); //隔行变色 if(count%2!==0){ //渐变写法 return 'l(90) 0:rgba(36, 149, 255, 0.7) 1:rgba(36, 149, 255, 0.1)' }else{ return 'l(90) 0:rgba(75, 215, 157, 0.7) 1:rgba(75, 215, 157, 0.1)' } }) .shape('triangle'); //坐标轴 chart.axis('value', { // 不展示 xField 对应坐标轴的标题 title: null, //网格虚线 grid: { line: { style: { stroke: '#d9d9d9', lineWidth: 1, lineDash: [2, 2], }, }, }, }); //控制间隔 chart.scale('value', { nice: true, tickInterval: 500, }); //所有提示都不展示 chart.tooltip(false); //所有图例都不展示 chart.legend(false); //交互:鼠标在画布上移动是,对应的区域出现背景框 chart.interaction('active-region'); chart.render();
Echarts:
import EchartsReact from 'echarts-for-react'; const Chart5e1 =()=>{ type data={name:string,value:number}[] let data:data = [ {name:'指挥中心',value:770}, {name:'科信',value:450}, {name:'刑侦',value:300}, {name:'XXX',value:255}, {name:'情报',value:203}, ] let xAxisData:any=[]; let seriesData:any=[]; let max=0; //因为边框也需要隔行变色,但是borderColor属性不支持函数方式,所以只能加到data中 data.forEach((item: any, index: number) => { if (item.value > max) { max = item.value; } if (index % 2 !== 0) { seriesData.push({ value: item.value, itemStyle: { borderColor: 'rgba(75, 215, 157, 0.7)', }, }); } else { seriesData.push({ value: item.value, itemStyle: { borderColor: 'rgba(36, 149, 255, 0.7)', }, }); } xAxisData.push(item.name); }); const option = { tooltip : { trigger: 'axis', axisPointer : { // 坐标轴指示器,坐标轴触发有效 type : 'none' // 默认为直线,可选为:'line' | 'shadow' }, backgroundColor:'#405685', textStyle : { color: '#E5EDF5', decoration: 'none', fontSize: 12, }, formatter:function(param){ let tip = ''; tip = param[0].name+': '+ param[0].value; return tip } }, grid: { //图表与外层div间距,可以理解为padding top: '8%', right: '10%', left: '15%', bottom: '15%' }, xAxis: { type: 'category', data: xAxisData, axisLine: { lineStyle: { color: '#C3C8CC' } }, axisTick: {show: false}, axisLabel: { color: '#000', textStyle: { fontSize: 12 }, formatter:function(value){ var ret = "";//拼接加\n返回的类目项 var maxLength = 4;//每项显示文字个数 var valLength = value.length;//X轴类目项的文字个数 var rowN = Math.ceil(valLength / maxLength); //类目项需要换行的行数 if (rowN > 1)//如果类目项的文字大于5, { var temp = "";//每次截取的字符串 var start = 0;//开始截取的位置 var end = maxLength;//结束截取的位置 temp = value.substring(start, end)+'\n'+value.substring(end, valLength) ret += temp; //凭借最终的字符串 return ret; } else{ return value; } }, }, splitLine: { show: false, } }, yAxis: { type: 'value', axisLabel: { formatter: function (value: any) { return parseInt(value); }, color: '#000', }, max:Math.ceil(max/500)*500, interval:500, axisLine:{show:false}, axisTick: {show: false}, splitLine: { lineStyle: { type:'dashed', // 使用深浅的间隔色 color: '#273858' } }, }, series: [{ data: seriesData, type: 'pictorialBar', barCategoryGap: '-20%', symbol: 'path://M2.08269 86.5C28.1667 72.8126 45.3971 46.8239 48 17.6787C50.6029 46.8239 67.8333 72.8126 93.9173 86.5H2.08269Z', itemStyle: { normal: { //图形的间隔变色,渐变 color:function(params){ if(params.dataIndex % 2 == 0){ return { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [{ offset: 0, color: 'rgba(36, 149, 255, 0.7)' // 0% 处的颜色 }, { offset: 1, color: 'rgba(36, 149, 255, 0.1)' // 100% 处的颜色 }], globalCoord: false // 缺省为 false } }else{ return { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [{ offset: 0, color: 'rgba(75, 215, 157, 0.7)' // 0% 处的颜色 }, { offset: 1, color: 'rgba(75, 215, 157, 0.1)' // 100% 处的颜色 }], globalCoord: false // 缺省为 false } } } // color:{ // type: 'linear', // x: 0, // y: 0, // x2: 0, // y2: 1, // colorStops: [{ // offset: 0, color: 'rgba(36, 149, 255, 0.7)' // 0% 处的颜色 // }, { // offset: 1, color: 'rgba(36, 149, 255, 0.1)' // 100% 处的颜色 // }], // globalCoord: false // 缺省为 false // } }, }, label: { normal: { show: true, position:'top', color:'#000', fontSize:14, formatter: function(params){ var str = ''; str = params.value; return str }, fontFamily: 'DINPro' }, }, z: 10 }, { name: 'glyph', type: 'pictorialBar', barGap: '-100%', symbolPosition: 'end', symbolSize: 50, symbolOffset: [0, '-120%'], }] }; return <EchartsReact option={option} style={{ width: '100%', height: '100%' }} />; } export default Chart5e1;
效果:
d.水波图组件(G2plot实现,个人感觉和G2没有太大区别)
组件:import { useEffect, useRef, useState } from 'react'; import { Liquid } from '@antv/g2plot'; //唯一id,颜色,数值,文本,大小 const LiquidChart=({ids,color,percent,textinfo,size})=>{ const [liquidPlot,setLiquidPlot]=useState(null) useEffect(()=>{ //数值更新销毁重绘 if(liquidPlot!==null){ liquidPlot.destroy() } const liquidPlot1 = new Liquid('sbchart'+ids, { //新建 percent: percent, //百分比 width:size, height:size, liquidStyle:{ //水波样式 fill:color, stroke:color }, statistic :{ //文本配置 title:{ formatter:(v)=>{ return v.percent*100+'%' }, style:{ fontSize:size/9, color: '#093049' } }, content:{ content:textinfo, style:{ fontSize:size/15, color: '#093049' } } } }); liquidPlot1.render(); setLiquidPlot(liquidPlot1) },[color,percent,textinfo,size]) return <div id={'sbchart'+ids}></div> } export default LiquidChart
使用
<LiquidChart ids={1} color={"#A595FE"} percent={cpu} textinfo={"CPU使用率"} size={220} > </LiquidChart>
e.曲线面积图表组件(G2plot实现)
组件
import { useEffect, useRef, useState } from 'react'; import { Line } from '@antv/g2plot'; const LineChart=({data,height,ids,legend=true,width,xAxis=true,yAxis=true})=>{ const [linePlot1,setLinePlot1]=useState(null) useEffect(()=>{ //数值更新销毁重绘 if(linePlot1!==null){ linePlot1.destroy() } const linePlot = new Line('box'+ids, { data, padding:'auto', xField: 'date', //x轴映射 yField: 'value', //y轴映射 height:height, seriesField: 'name', //拆分字段,在分组条形图下同 groupField、colorField,在堆积条形图下同 stackField、colorField。 width:width, yAxis: yAxis?{ label: { formatter: (v) => `${v}`, }, grid:{ line:{ style:{ lineDash:[4,5] //设置轴线为虚线 } } } }:false, xAxis: xAxis? { range: [0, 1], //从x轴起点开始画,画到最后,不会存在与y轴存在间距 label: { formatter: (v) => { return v }, }, }:false, legend: legend?{ position: 'top-left', //设置图例位置 }:false, tooltip: { formatter: (datum) => { return { name: datum.name, value: datum.value + 'Mbps' }; //设置提示 }, }, smooth: true, // 配置折线趋势填充 area: { style: ({ name }) => { const { colors10 } = linePlot.chart.getTheme(); return { fill: name === '接入宽带' ? `l(90) 0.3:${colors10[0]} 1:rgba(255,255,255,0.2)` : `l(90) 0.3:${colors10[1]} 1:rgba(255,255,255,0.2)`, }; }, }, animation: { appear: { animation: 'wave-in', duration: 3000, }, }, }); linePlot.render(); setLinePlot1(linePlot) },[data]) return <div id={"box"+ids}></div> } export default LineChart
使用
const dataarr=[ { name: "输入宽带", date:'1s', value: 82 }, { name: "输出宽带", date:'1s', value: 150 }, { name: "输入宽带", date:'2s', value: 96 }, { name: "输出宽带", date:'2s', value:126 }, ] <LineChart data={dataarr} height={240} ids={1} ></LineChart>
f.双向柱状图(G2plot实现)
const [max,setMax]=useState(0) const devicedata = [ { type: `单通道设备视频通道`, sales: 150,aname:1 }, { type: `单通道设备视频通道`, sales: -15,aname:0 }, { type: `多通道设备视频通道`, sales: 120,aname:2 }, { type: `多通道设备视频通道`, sales: -120,aname:0 } ] let max=0 devicedata.forEach(item=>{ if(Math.abs(item.sales)>max){ max=Math.abs(item.sales) } }) setMax(max) useEffect(()=>{ if(bar1!==null){ bar1.destroy() } const bar = new Bar('container', { data:devicedata, xField: 'sales', yField: 'type', meta: { // sales映射的最大最小值 sales: { max: max, min: -max, //防止出现数据只有正值,导致负值的半轴不显示 } }, legend: { position: 'top-left', }, width:500, yAxis:{ label:{ formatter: (v) => { if(v==="多通道设备视频通道"){ //y轴文本换行 return `多通道设备 视频通道` } return `单通道设备 视频通道` }, }, }, xAxis:{ grid:{ line:{ style:{ lineDash:[4,5] //x轴线虚线 } } }, barWidthRatio:0.2, //柱子宽度 seriesField: 'aname', // 部分图表使用 seriesField //设置正值不同类颜色不同,负值都为灰色 color: ({ aname }) => { if(aname === 0){ return '#8E9DAF'; }else if(aname===1){ return '#4DAAFF'; } return '#13C2C2'; }, tooltip:{ formatter: (datum) => { return { name: datum.aname!==0?'在线':'离线', value: Math.abs(datum.sales) }; }, title:(v)=>{ return v.trim()+'(个)' } }, legend:false, barBackground: { style: { fill: 'rgba(0,0,0,0.1)', borderRadius:50 }, }, interactions: [{ type: 'active-region', enable: false }], }); bar.render(); setbar1(bar) },[devicedata,max])
**
g.曲线图(自定义面积渐变,自定义图例,自定义x绘画区域,边框)
const AreasplineChart = ({id,className}:{id:string,className?:string}) => { const data = [ { "year": "1", "value": 4055, "category": "人脸" }, { "year": "1", "value": 1756, "category": "人体" }, { "year": "1", "value": 5664, "category": "机动车" }, { "year": "1", "value": 6004, "category": "非机动车" }, { "year": "2", "value": 2106, "category": "人脸" }, { "year": "2", "value": 1783, "category": "人体" }, { "year": "2", "value": 5019, "category": "机动车" }, { "year": "2", "value": 1005, "category": "非机动车" }, .... ........ ] const fillcolor = [ { type:'人脸', color:'l(90) 0.1:rgba(77, 170, 255, 0.3) 1:rgba(255,255,255,0.1)', }, { type:'人体', color:'l(90) 0.1:rgba(165, 149, 254, 0.3) 1:rgba(255,255,255,0.1)', }, { type:'机动车', color:'l(90) 0.1:rgba(32, 203, 206, 0.3) 1:rgba(255,255,255,0.1)', }, { type:'非机动车', color:'l(90) 0.1:rgba(255, 170, 91, 0.3) 1:rgba(255,255,255,0.1)' } ] useEffect(()=>{ const line = new Line('container'+id, { data, xField: 'year', yField: 'value', seriesField: 'category', appendPadding:[24,0,0,0], height:220, xAxis:{ //去除x轴的刻度线 tickLine:null //定义画图区域,默认从第一个刻度开始,这样设置会从0开始画 //range: [0, 1], }, yAxis: { label: { // 数值格式化为千分位 formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`), }, //y轴值的间隔 tickInterval:2000, grid:{ line:{ style:{ lineDash:[4,5] //设置轴线为虚线 } } } }, legend: { position: 'top-left', itemWidth:80, //自定义图例的图标形状 marker:{ //内置类型 symbol:'square', style:(value)=>{ return { fill: value.stroke, lineJoin: "round", lineWidth: 6, r: 2, stroke: value.stroke, } } } }, //是否为圆滑曲线,false为折线图 smooth: true, //设置线颜色 color:['rgba(77, 170, 255, 1)','rgba(165, 149, 254, 1)','rgba(32, 203, 206, 1)','rgba(255, 170, 91, 1)'], // 配置折线趋势填充 area: { style: ({category}) => { return { fill: fillcolor.filter(v=>v.type===category)[0].color }; }, }, }); line.render(); },[]) return ( <div id={`container${id}`} className={className}></div> ) }
h.折线图(自定义背景,自定义节点样式)
const StockPendingChart = ({id}:{id:string}) => { let data:object[]=[] for(let i=0;i<24;i++){ data.push( { "year": `${i<10?'0'+i : i}:00`, "value": Math.random()*10000, "category": "人脸" } ); data.push( { "year": `${i<10?'0'+i : i}:00`, "value": Math.random()*10000, "category": "人体" } ); data.push( { "year": `${i<10?'0'+i : i}:00`, "value": Math.random()*10000, "category": "机动车" } ); data.push( { "year": `${i<10?'0'+i : i}:00`, "value": Math.random()*10000, "category": "非机动车" } ); } const [typechart,setTypechart]=useState(null) useEffect(()=>{ const line = new Line('container'+id, { data, xField: 'year', yField: 'value', seriesField: 'category', height:200, //可以理解为图表与图例之间那些的间距 appendPadding:[24,0,0,0], xAxis: { nice: true, label: { formatter: (name) => name, }, // 坐标轴线的配置项 null 表示不展示 tickLine:null, grid: { line: { style: { //设置x轴的那个灰色背景 lineWidth:42, stroke: 'rgba(239, 242, 244, 0.5)', }, }, }, }, yAxis: { label: { // 数值格式化为千分位 formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`), }, tickInterval:2000, grid:{ line:{ style:{ lineDash:[4,5] //设置轴线为虚线 } } } }, legend: { position: 'top-left', marker:{ symbol:'square', style:(value)=>{ return { fill: value.stroke, lineJoin: "round", lineWidth: 6, r: 2, stroke: value.stroke, } } } }, //配置折线图每个节点的样式 point: { size: 5, style: { lineWidth: 1, fillOpacity: 1, }, shape: 'circle' }, // 配置折线线条颜色 color:['rgba(77, 170, 255, 1)','rgba(165, 149, 254, 1)','rgba(32, 203, 206, 1)','rgba(255, 170, 91, 1)'], }); line.render(); },[]) return ( <div id={`container${id}`} style={{flex:'1'}}></div> ) }
I.环图(自定义图例样式,G2plot ,G2分别实现)
//G2plot 实现 import React, { useEffect, useState } from "react"; import { Pie } from "@antv/g2plot"; import { TransNumber } from "@src/pages/utils"; export interface chartdata { type: string; value: number; } const PieChart = ({ id, datasouce }: { id: string, datasouce: chartdata[] }) => { const [typechart, setTypechart] = useState<any>(null) useEffect(() => { if (typechart) { typechart.destroy() } const piePlot = new Pie('container'+id, { data:datasouce, height:260, legend:{ //图例项水平布局 layout: 'horizontal', position: 'right', offsetX:-20, //是否分页 flipPage:false, //图例项水平间距 itemSpacing:24, //图例项垂直间距 itemMarginBottom:34, //图例与图形的占比 maxWidthRatio:0.6, //图例图标 marker:{ symbol:'square' }, itemWidth:120, //图例名 itemName:{ style:{ fontSize:14 } }, //图例值 itemValue:{ //水平居右 alignRight:true, formatter(text) { return TransNumber(datasouce?.filter(item=>item.type===text)[0].value) }, style:{ fontSize:14 } } }, //空白间距 pieStyle:{ lineWidth:6 }, angleField: 'value', colorField: 'type', radius: 0.6, innerRadius: 0.6, label: false, interactions: [{ type: 'element-selected' }, { type: 'element-active' }], statistic: undefined, }); piePlot.render(); setTypechart(piePlot) }, [datasouce]) return ( <div id={`container${id}`}></div> ) } export default PieChart
//G2 实现 const ChildrenTypeChart = () => { const [typechart,setTypechart]=useState(null) useEffect(()=>{ if(typechart!==null){ typechart.destroy() } const data = [ { type: '消费连接异常', value: 15 }, { type: '任务启动异常', value: 15 }, { type: '网络连接异常', value: 10 }, { type: '数据库异常', value: 10 }, { type: '服务自身异常', value: 10 }, { type: '其他', value: 10 }, ]; // 可以通过调整这个数值控制分割空白处的间距,0-1 之间的数值 const sliceNumber = 0.01; // 自定义 other 的图形,增加两条线 registerShape('interval', 'slice-shape', { draw(cfg, container) { const points= cfg.points; let path = []; path.push(['M', points[0].x, points[0].y]); path.push(['L', points[1].x, points[1].y - sliceNumber]); path.push(['L', points[2].x, points[2].y - sliceNumber]); path.push(['L', points[3].x, points[3].y]); path.push('Z'); path = this.parsePath(path); return container.addShape('path', { attrs: { fill: cfg.color, path, }, }); }, }); const chart = new Chart({ container: 'container', autoFit: true, height: 300, width:270 }); chart.legend({ flipPage:false, itemWidth:120 }); chart.data(data); chart.coordinate('theta', { radius: 0.55, innerRadius: 0.65, }); chart.tooltip({ showTitle: false, showMarkers: false, }); chart .interval() .adjust('stack') .position('value') .color('type') .shape('slice-shape'); chart.render(); setTypechart(chart) },[]) return ( <div id="container"></div> ) }
J.柱状图(自定义背景)
import React, { useEffect, useState } from "react"; import { Column } from '@antv/g2plot'; export interface chartdata { name: string; value: number; type: string; } const ClounmChart = ({ id, datasouce }: { id: string, datasouce: chartdata[] }) => { const [typechart, setTypechart] = useState<any>(null) useEffect(() => { if (typechart) { typechart.destroy() } const stackedColumnPlot = new Column('container' + id, { data: datasouce, isStack: true, //是否累叠 xField: 'name', height: 240, appendPadding:[20,0,0,0], yField: 'value', legend: { position: 'top-right', }, xAxis: { nice: true, // 坐标轴线的配置项 null 表示不展示 tickLine: null, grid: { line: { style: { lineWidth: 36, //背景宽度 lineDash: [4, 4], //背景虚线,不要这个就是第二张图 stroke: 'rgba(238, 239, 243, 1)', //背景颜色 }, }, }, }, yAxis: { label: { // 数值格式化为千分位 formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`), }, // tickInterval:2000, grid: { line: { style: { lineDash: [4, 5] //设置轴线为虚线 } } } }, seriesField: 'type', columnWidthRatio: 0.2, }); stackedColumnPlot.render(); setTypechart(stackedColumnPlot) }, [datasouce]) return ( <div id={`container${id}`}></div> ) } export default ClounmChart
K.分组柱状图(自定义形状样式,间距等)
import { useEffect, useState } from "react"; import { Column } from '@antv/g2plot'; const ColumnGroupChart = ({ id, currentDetail }: { id: string, currentDetail: any }) => { const [currentChart, setCurrentChart] = useState<any>(null) const types = ['数据消费数量', '数据转换成功数量', '数据转换失败数量 ', '数据入库成功数量', '数据入库失败数量'] useEffect(() => { let data: any[] = [] currentDetail?.detailData?.forEach((item: any) => { data.push({ type: types[item.type-1], datatype: "人脸", value: item?.faceCount }) data.push({ type: types[item.type-1], datatype: "人体", value: item?.bodyCount }) data.push({ type: types[item.type-1], datatype: "机动车", value: item?.faceCount }) data.push({ type: types[item.type-1], datatype: "非机动车", value: item?.nomotorVehicleCount }) }); if (currentChart) { currentChart.destroy() } const column = new Column('container' + id, { data: data, xField: 'type', yField: 'value', height: 400, seriesField: 'datatype', isGroup: true, appendPadding: [24, 0, 0, 0], // intervalPadding:160, maxColumnWidth: 16, xAxis: { tickLine: null, }, yAxis: { label: { // 数值格式化为千分位 formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`), }, grid: { line: { style: { lineDash: [4, 5] //设置轴线为虚线 } } } }, legend: { position: 'top-left', marker: { symbol: 'square', style: (value) => { return { fill: value.fill, lineJoin: "round", lineWidth: 6, r: 2, stroke: value.fill, } } } }, columnStyle: { radius: [20, 20, 20, 20], }, columnBackground: { style: { fill: 'rgba(245, 245, 245, 1)' } }, color: ['rgba(77, 170, 255, 1)', 'rgba(165, 149, 254, 1)', 'rgba(32, 203, 206, 1)', 'rgba(255, 170, 91, 1)'], }); column.render(); setCurrentChart(column) // eslint-disable-next-line react-hooks/exhaustive-deps }, []) return <div id={`container${id}`} style={{ marginTop: '40px' }}></div> } export default ColumnGroupChart
-
antv-g2plot-master_java_
2021-10-03 02:05:41G6 是一个图可视化框架。它提供了一套图可视化的基础设置,能帮助开发者搭建属于自己的图 图分析 应用或是 图编辑器 应用 -
AntV | 蚂蚁数据可视化 G2Plot 快速入门
2021-11-11 09:10:46AntV | 蚂蚁数据可视化 G2Plot 快速入门 G2Plot 是一套简单、易用、并具备一定扩展能力和组合能力的统计图表库,基于图形语法理论搭建而成。AntV | G2Plot API
AntV | G2Plot 教程1、开始
<1> 简介
G2Plot 是一套简单、易用、并具备一定扩展能力和组合能力的统计图表库,基于图形语法理论搭建而成。
特性:
- 📦 开箱即用、默认好用的高质量统计图表
- 🎨 提炼自企业级产品的视觉语言和设计规范
- 📊 响应式图表:致力于解决图表在任何数据和显示尺寸下的基本可读性问题
- 🔳 图层化设计方法:在 G2Plot 体系下,图表不仅仅只是各不相关的实例,图层概念的引入提供了多图表组合叠联动,共同讲述一个数据故事的可能性
<2> npm安装
$ npm install @antv/g2plot
<3> 使用
index.html<div id="container"></div>
index.js
import { Bar } from '@antv/g2plot'; const data = [ { year: '1951 年', value: 38 }, { year: '1952 年', value: 52 }, { year: '1956 年', value: 61 }, { year: '1957 年', value: 45 }, { year: '1958 年', value: 48 }, ]; const bar = new Bar('container', { data, xField: 'value', yField: 'year', seriesField: 'year', legend: { position: 'top-left', }, }); bar.render();
package.json
{ "name": "b4zgu5--run", "version": "0.0.0", "private": true, "dependencies": { "react": "17.0.2", "react-dom": "17.0.2", "@antv/g2plot": "2.3.39" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }, "devDependencies": { "react-scripts": "latest" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
<4> 开发
# 安装依赖性 $ npm install # 运行测试用例 $ npm run test # 建立和运行网站,观察文件变化 $ npm run start
<5> 浏览器引入
<!-- 引入在线资源 --> <script type="text/javascript" src="https://unpkg.com/@antv/g2plot@latest/dist/g2plot.min.js"></script> <script> const { Line } = G2Plot; </script>
<!-- 下载到本地 引入本地脚本 --> <script src="./g2plot.min.js"></script> <script> const { Line } = G2Plot; </script>
2、折线图
import { Line } from '@antv/g2plot';
<1> 快速上手
import { Line } from '@antv/g2plot'; const data = [ { year: '2016 年', value: 1770 }, { year: '2017 年', value: 2540 }, { year: '2018 年', value: 1850 }, { year: '2019 年', value: 4101 }, { year: '2020 年', value: 3333 }, ]; const line = new Line('container', { data, xField: 'year', yField: 'value', }); line.render();
<2>.浏览器引入
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="container" /> <!-- 下载到本地 引入本地脚本 --> <script src="g2plot.min.js"></script> <!-- 引入在线资源 --> <!-- <script type="text/javascript" src="https://unpkg.com/@antv/g2plot@latest/dist/g2plot.min.js"></script> --> <script src="test5.js"></script> </body> </html>
test1.js
const { Line } = G2Plot; const data = [ { year: '2016 年', value: 1770 }, { year: '2017 年', value: 2540 }, { year: '2018 年', value: 1850 }, { year: '2019 年', value: 4101 }, { year: '2020 年', value: 3333 }, ]; const line = new Line('container', { data, xField: 'year', yField: 'value', }); line.render();
<3> 引入json数据
【1】外部引入json数据:
// index.js import { Line } from '@antv/g2plot'; fetch('https://gw.alipayobjects.com/os/bmw-prod/1d565782-dde4-4bb6-8946-ea6a38ccf184.json') .then((res) => res.json()) .then((data) => { const line = new Line('container', { data, xField: 'Date', yField: 'scales', }); line.render(); });
【2】内部引入json数据:
import {Line} from '@antv/g2plot'; fetch('http://127.0.0.1:5000/data.json') .then((res) => res.json()) .then((data) => { const line = new Line('container', { data, xField: 'Date', yField: 'scales', }); line.render(); });
<3> 折线图特性
【1】曲线图
曲线图是用曲线将一系列的数据点连接的图表, 对应的只需要配置
smooth: true
属性即可。const line = new Line('container', { data, xField: 'year', yField: 'value', smooth: true });
【2】阶梯型直线图
对应的只需要配置
stepType
属性即可。options: { stepType: 'vh' // 可选项:hv | vh | hvh | vhv }
const line = new Line('container', { data, xField: 'year', yField: 'value', stepType: 'vh', });
3、柱状图
import { Column } from '@antv/g2plot';
<1> 快速上手
npm 方式引入:
import { Column } from '@antv/g2plot';
浏览器引入:const {Column} = G2Plot;
import { Column } from '@antv/g2plot'; fetch('https://gw.alipayobjects.com/os/antfincdn/8elHX%26irfq/stack-column-data.json') .then((data) => data.json()) .then((data) => { const stackedColumnPlot = new Column('container', { data, isStack: true, xField: 'year', yField: 'value', seriesField: 'type', label: { // 可手动配置 label 数据标签位置 position: 'middle', // 'top', 'bottom', 'middle' // 可配置附加的布局方法 layout: [ // 柱形图数据标签位置自动调整 { type: 'interval-adjust-position' }, // 数据标签防遮挡 { type: 'interval-hide-overlap' }, // 数据标签文颜色自动调整 { type: 'adjust-color' }, ], }, }); stackedColumnPlot.render(); });
<2> 柱状图特性
【1】堆叠柱状图
使用颜色不同的堆叠的柱形来显示各维度的数值。横轴标示出第一个分类维度,颜色标示出第二个分类维度,纵轴显示相应的值。
通过指定
seriesField
且设置isStack: true
就可以创建堆叠柱状图。const stackedColumnPlot = new Column('container', { data, isStack: true, /*...*/ });
const {Column} = G2Plot; const data = [{ "year": "1991", "value": 3, "type": "Lon" }, { "year": "1992", "value": 4, "type": "Lon" }, { "year": "1993", "value": 3.5, "type": "Lon" }, { "year": "1994", "value": 5, "type": "Lon" }, { "year": "1995", "value": 4.9, "type": "Lon" }, { "year": "1996", "value": 6, "type": "Lon" }, { "year": "1997", "value": 7, "type": "Lon" }, { "year": "1998", "value": 9, "type": "Lon" }, { "year": "1999", "value": 13, "type": "Lon" }, { "year": "1991", "value": 3, "type": "Bor" }, { "year": "1992", "value": 4, "type": "Bor" }, { "year": "1993", "value": 3.5, "type": "Bor" }, { "year": "1994", "value": 5, "type": "Bor" }, { "year": "1995", "value": 4.9, "type": "Bor" }, { "year": "1996", "value": 6, "type": "Bor" }, { "year": "1997", "value": 7, "type": "Bor" }, { "year": "1998", "value": 9, "type": "Bor" }, { "year": "1999", "value": 13, "type": "Bor" } ]; const stackedColumnPlot = new Column('container', { data, isStack: true, xField: 'year', yField: 'value', seriesField: 'type', label: { // 可手动配置 label 数据标签位置 position: 'middle', // 'top', 'bottom', 'middle' // 可配置附加的布局方法 layout: [ // 柱形图数据标签位置自动调整 {type: 'interval-adjust-position'}, // 数据标签防遮挡 {type: 'interval-hide-overlap'}, // 数据标签文颜色自动调整 {type: 'adjust-color'}, ], }, }); stackedColumnPlot.render();
【2】分组柱状图
const stackedColumnPlot = new Column('container', { data, isGroup: true, /*...*/ });
const {Column} = G2Plot; const data = [ { name: 'London', 月份: 'Jan.', 月均降雨量: 18.9, }, { name: 'London', 月份: 'Feb.', 月均降雨量: 28.8, }, { name: 'London', 月份: 'Mar.', 月均降雨量: 39.3, }, { name: 'London', 月份: 'Apr.', 月均降雨量: 81.4, }, { name: 'London', 月份: 'May', 月均降雨量: 47, }, { name: 'London', 月份: 'Jun.', 月均降雨量: 20.3, }, { name: 'London', 月份: 'Jul.', 月均降雨量: 24, }, { name: 'London', 月份: 'Aug.', 月均降雨量: 35.6, }, { name: 'Berlin', 月份: 'Jan.', 月均降雨量: 12.4, }, { name: 'Berlin', 月份: 'Feb.', 月均降雨量: 23.2, }, { name: 'Berlin', 月份: 'Mar.', 月均降雨量: 34.5, }, { name: 'Berlin', 月份: 'Apr.', 月均降雨量: 99.7, }, { name: 'Berlin', 月份: 'May', 月均降雨量: 52.6, }, { name: 'Berlin', 月份: 'Jun.', 月均降雨量: 35.5, }, { name: 'Berlin', 月份: 'Jul.', 月均降雨量: 37.4, }, { name: 'Berlin', 月份: 'Aug.', 月均降雨量: 42.4, }, ]; const stackedColumnPlot = new Column('container', { data, isGroup: true, xField: '月份', yField: '月均降雨量', seriesField: 'name', /** 设置颜色 */ // color: ['#1ca9e6', '#f88c24'], /** 设置间距 */ // marginRatio: 0.1, label: { // 可手动配置 label 数据标签位置 position: 'middle', // 'top', 'middle', 'bottom' // 可配置附加的布局方法 layout: [ // 柱形图数据标签位置自动调整 { type: 'interval-adjust-position' }, // 数据标签防遮挡 { type: 'interval-hide-overlap' }, // 数据标签文颜色自动调整 { type: 'adjust-color' }, ], }, }); stackedColumnPlot.render();
【3】指定柱子最大宽度、最小宽度
const columnPlot = new Column('container', { /*...*/ minColumnWidth: 20, maxColumnWidth: 50, });
const {Column} = G2Plot; const data = [ { type: '家具家电', sales: 38, }, { type: '粮油副食', sales: 52, }, { type: '生鲜水果', sales: 61, }, { type: '美容洗护', sales: 145, } ]; const columnPlot = new Column('container', { data, xField: 'type', yField: 'sales', xAxis: { label: { autoHide: true, autoRotate: false, }, }, meta: { type: { alias: '类别', }, sales: { alias: '销售额', }, }, minColumnWidth: 20, maxColumnWidth: 50, }); columnPlot.render();
【4】设置柱子的圆角
const column = new Column('container', { /*...*/ columnStyle: { radius: [20, 20, 0, 0], }, });
const {Column} = G2Plot; const data = [ { "city": "杭州", "type": "水果", "value": 9000 }, { "city": "杭州", "type": "米面", "value": 8500 }, { "city": "杭州", "type": "特产零食", "value": 10000 }, { "city": "杭州", "type": "茶叶", "value": 6000 }, { "city": "北京", "type": "水果", "value": 17000 }, { "city": "北京", "type": "米面", "value": 6000 }, { "city": "北京", "type": "特产零食", "value": 7000 }, { "city": "北京", "type": "茶叶", "value": 10000 }, { "city": "上海", "type": "水果", "value": 18000 }, { "city": "上海", "type": "米面", "value": 11000 }, { "city": "上海", "type": "特产零食", "value": 15000 }, { "city": "上海", "type": "茶叶", "value": 14000 } ]; const column = new Column('container', { data, xField: 'city', yField: 'value', seriesField: 'type', isGroup: 'true', columnStyle: { radius: [20, 20, 0, 0], }, }); column.render();
【5】设置柱子的背景样式
通过设置
columnBackground.style
可以指定柱子的背景样式。const column = new Column('container', { /*...*/ columnBackground: { style: { fill: 'rgba(170, 170, 255, 1.0)', }, }, });
const {Column} = G2Plot; const data = [ { "city": "杭州", "type": "水果", "value": 9000 }, { "city": "北京", "type": "茶叶", "value": 10000 }, { "city": "上海", "type": "茶叶", "value": 14000 } ]; const column = new Column('container', { data, xField: 'city', yField: 'value', seriesField: 'type', isGroup: 'true', columnBackground: { style: { fill: 'rgba(170, 170, 255, 1.0)', }, }, }); column.render();
4、条形图
import { Bar } from '@antv/g2plot';
<1>快速上手
const {Bar} = G2Plot const data = [ { year: '1951 年', value: 38 }, { year: '1952 年', value: 52 }, { year: '1956 年', value: 61 }, { year: '1957 年', value: 145 }, { year: '1958 年', value: 48 }, ]; const bar = new Bar('container', { data, xField: 'value', yField: 'year', seriesField: 'year', legend: { position: 'top-left', }, }); bar.render();
<2> 条形图特性
【1】指定柱子最大宽度、最小宽度(同柱状图)
const barPlot = new Bar('container', { /*...*/ minBarWidth: 20, maxBarWidth: 20, });
【2】设置柱子的圆角(同柱状图)
const stackedBarPlot = new Bar('container', { /*...*/ barStyle: { radius: [2, 2, 0, 0] }, });
5、面积图
import { Area } from '@antv/g2plot'; fetch('https://gw.alipayobjects.com/os/bmw-prod/360c3eae-0c73-46f0-a982-4746a6095010.json') .then((res) => res.json()) .then((data) => { const area = new Area('container', { data, xField: 'timePeriod', yField: 'value', meta: { timePeriod: { range: [0, 1], }, }, }); area.render(); });
6、色块图 / 热力图
色块图,由小色块组成的图表。色块图的最大好处是,2 维画布上的空间利用率高。7、 仪表盘
import { Gauge } from '@antv/g2plot';
import { Gauge } from '@antv/g2plot'; const gauge = new Gauge('container', { percent: 0.75, range: { color: '#5B8FF9', }, statistic: { content: { formatter: ({ percent }) => `Rate: ${(percent * 100).toFixed(0)}%`, }, }, }); gauge.render();
<1>.自定义指示器的样式
通过设置
indicator
来自定义指示器的样式,指示器包含指针pointer
和 指针针头pin
样式。import { Gauge } from '@antv/g2plot'; const gauge = new Gauge('container', { percent: 0.75, range: { color: '#30BF78', }, indicator: {//自定义指示器的样式 pointer: { style: { stroke: '#D0D0D0', }, }, pin: { style: { stroke: '#D0D0D0', }, }, }, axis: { label: { formatter(v) { return Number(v) * 100; }, }, subTickLine: { count: 3, }, }, statistic: { content: { formatter: ({ percent }) => `Rate: ${(percent * 100).toFixed(0)}%`, style: { color: 'rgba(0,0,0,0.65)', fontSize: 48, }, }, }, }); gauge.render();
<2> 自定义辅助圆弧的样式
通过设置
range
的 ‘ticks’’ 和 ‘color’ 来自定义辅助圆弧的样式// 代表着,0 - 1/3: #F4664A, 1/3 - 2/3: #FAAD14, 2/3 - 1: #30BF78 { range: { ticks: [0, 1/3, 2/3, 1], color: ['#F4664A', '#FAAD14', '#30BF78'], }, }
import { Gauge } from '@antv/g2plot'; const gauge = new Gauge('container', { percent: 0.75, range: { ticks: [0, 1 / 3, 2 / 3, 1], color: ['#F4664A', '#FAAD14', '#30BF78'], }, indicator: { pointer: { style: { stroke: '#D0D0D0', }, }, pin: { style: { stroke: '#D0D0D0', }, }, }, statistic: { content: { style: { fontSize: '36px', lineHeight: '36px', }, }, }, }); gauge.render();
8、饼图
import { Pie } from '@antv/g2plot'; const data = [ { type: '分类一', value: 27 }, { type: '分类二', value: 25 }, { type: '分类三', value: 18 }, { type: '分类四', value: 15 }, { type: '分类五', value: 10 }, { type: '其他', value: 5 }, ]; const piePlot = new Pie('container', { data, angleField: 'value', colorField: 'type', }); piePlot.render();
<1> 饼图特性:
【1】环图
在 G2Plot 中,只需要指定
innerRadius
就可以创建环形饼图const piePlot = new Pie('container', { /*...*/ innerRadius: 0.6 /*...*/ )};
import { Pie } from '@antv/g2plot'; const data = [ { type: '分类一', value: 27 }, { type: '分类二', value: 25 }, { type: '分类三', value: 18 }, { type: '分类四', value: 15 }, { type: '分类五', value: 10 }, { type: '其他', value: 5 }, ]; const piePlot = new Pie('container', { appendPadding: 10, data, angleField: 'value', colorField: 'type', radius: 1, innerRadius: 0.6, label: { type: 'inner', offset: '-50%', content: '{value}', style: { textAlign: 'center', fontSize: 14, }, }, interactions: [{ type: 'element-selected' }, { type: 'element-active' }], statistic: { title: false, content: { style: { whiteSpace: 'pre-wrap', overflow: 'hidden', textOverflow: 'ellipsis', }, content: 'AntV\nG2Plot', }, }, }); piePlot.render();
【3】扇形图
通过设置饼图的
startAngle
(开始角度) 和endAngle
(结束角度),我们可以将饼图变成扇形图const piePlot = new Pie('container', { /*...*/ // 设置圆弧起始角度 startAngle: Math.PI, endAngle: Math.PI * 1.5, /*...*/ });
import { Pie } from '@antv/g2plot'; const data = [ { type: '分类一', value: 27 }, { type: '分类二', value: 25 }, { type: '分类三', value: 18 }, { type: '分类四', value: 15 }, { type: '分类五', value: 10 }, { type: '其他', value: 5 }, ]; const piePlot = new Pie('container', { appendPadding: 10, data, angleField: 'value', colorField: 'type', radius: 1, // 设置圆弧起始角度 startAngle: Math.PI, endAngle: Math.PI * 1.5, label: { type: 'inner', offset: '-8%', content: '{name}', style: { fontSize: 18 }, }, interactions: [{ type: 'element-active' }], pieStyle: { lineWidth: 0, }, }); piePlot.render();
9、直方图
10、子弹图
11、瀑布图
12、水波图
13、雷达图
14、散点图
14、小提琴图
16、分面图
17、韦恩图
-
antv g2plot可视化图表在vue中的使用之三:图表皮肤主题theme配置
2020-09-22 16:28:39文章目录参考资料 参考资料 https://www.yuque.com/antv/g2-docs/tutorial-theme 语雀AntV/G2 文档 https://zhuanlan.zhihu.com/p/60812943 知乎antv 修改主题...https://github.com/antvis/G2Plot/issues/1226简介
接前一篇文章,本文使用antv g2plot对vue中的图表皮肤主题theme进行配置。
修改图表皮肤主题theme
以折线图为例,原始代码为
//src/views/Line.vue <template> <div id="linechart"></div> </template> <script> import { Line } from '@antv/g2plot' export default { mounted () { const data = [ { year: '1991', value: 3 }, { year: '1992', value: 4 }, { year: '1993', value: 3.5 }, { year: '1994', value: 5 }, { year: '1995', value: 4.9 }, { year: '1996', value: 6 }, { year: '1997', value: 7 }, { year: '1998', value: 9 }, { year: '1999', value: 13 }, ]; const linePlot = new Line('linechart', { title: { visible: true, text: '折线图', }, description: { visible: true, text: '用平滑的曲线代替折线。', }, data, xField: 'year', yField: 'value', }); linePlot.render(); } } </script>
修改主题为暗黑风格,在参数中添加theme: 'dark’即可。参照文档https://github.com/antvis/G2Plot/blob/master/docs/common/theme.zh.md。主题支持 light、 dark 两种模式,当然也可以自己指定, 默认使用 light。
//src/views/Line.vue <template> <div id="linechart"></div> </template> <script> import { Line } from '@antv/g2plot' export default { mounted () { const data = [ { year: '1991', value: 3 }, { year: '1992', value: 4 }, { year: '1993', value: 3.5 }, { year: '1994', value: 5 }, { year: '1995', value: 4.9 }, { year: '1996', value: 6 }, { year: '1997', value: 7 }, { year: '1998', value: 9 }, { year: '1999', value: 13 }, ]; const linePlot = new Line('linechart', { title: { visible: true, text: '折线图', }, description: { visible: true, text: '用平滑的曲线代替折线。', }, data, theme: 'dark', //设置为暗黑主题。主题支持 light、 dark 两种模式,当然也可以自己指定, 默认使用 light。 xField: 'year', yField: 'value', }); linePlot.render(); } } </script>
或者将渲染图表放在函数showLine里:
//src/views/Line.vue <template> <div id="linechart"></div> </template> <script> import { Line } from '@antv/g2plot' export default { data(){ return { linePlot: null, data: [{ year: '1991', value: 3 }, { year: '1992', value: 4 }, { year: '1993', value: 3.5 }, { year: '1994', value: 5 }, { year: '1995', value: 4.9 }, { year: '1996', value: 6 }, { year: '1997', value: 7 }, { year: '1998', value: 9 }, { year: '1999', value: 13 }, ] } }, mounted () { this.showLine(); }, methods: { showLine(){ let data = this.data this.linePlot = new Line('linechart', { title: { visible: true, text: '折线图', }, description: { visible: true, text: '用平滑的曲线代替折线。', }, data, theme: 'dark', xField: 'year', yField: 'value', }); this.linePlot.render(); } } } </script>
暗黑风格效果如图:
自定义背景颜色
也可以对theme设置自己喜欢的颜色backgroundStyle:
//src/views/Line.vue <template> <div id="linechart"></div> </template> <script> import { Line } from '@antv/g2plot' export default { mounted () { const data = [ { year: '1991', value: 3 }, { year: '1992', value: 4 }, { year: '1993', value: 3.5 }, { year: '1994', value: 5 }, { year: '1995', value: 4.9 }, { year: '1996', value: 6 }, { year: '1997', value: 7 }, { year: '1998', value: 9 }, { year: '1999', value: 13 }, ]; const linePlot = new Line('linechart', { title: { visible: true, text: '折线图', }, description: { visible: true, text: '用平滑的曲线代替折线。', }, data, theme: { backgroundStyle: { fill: '#FFD6E7', }, }, xField: 'year', yField: 'value', }); linePlot.render(); } } </script>
效果如下:
全局主题配置源码common.ts
g2plot的github源码地址https://github.com/antvis/G2Plot/blob/master/src/adaptor/common.ts
//https://github.com/antvis/G2Plot/blob/master/src/adaptor/common.ts /** * 设置全局主题配置 * @param params */ export function theme<O extends Pick<Options, 'theme'>>(params: Params<O>): Params<O> { const { chart, options } = params; const { theme } = options; // 存在主题才设置主题 if (theme) { chart.theme(theme); } return params; }
在各个图表源码下引用了theme,如:
import { theme, scale, animation, annotation, tooltip } from '../../adaptor/common';
G2Plot 继承 G2 自定义主题机制
G2Plot 继承 G2 的自定义主题机制,见详细文档。
G2 提供了自定义主题机制以允许用户切换、定义图表主题。包括:- 定义全新的主题结构
- 使用主题样式表,实现主题的快速定制
可参考https://github.com/antvis/G2Plot/tree/master/examples/general/theme
https://github.com/antvis/G2Plot/blob/master/examples/general/theme/API.zh.md//G2自定义主题机制 import { registerTheme, Chart } from '@antv/g2'; // Step 1: 注册主题 registerTheme('newTheme', { defaultColor: 'red', }); // Step 2: 使用 chart.theme('newTheme'); chart.render();
本文使用g2plot,参照github源码examples/general/theme/demo/register-theme.ts样例进行改造
//https://github.com/antvis/G2Plot/blob/master/examples/general/theme/demo/register-theme.ts import { Pie, G2 } from '@antv/g2plot'; const { registerTheme } = G2; registerTheme('custom-theme', { colors10: ['#FACDAA', '#F4A49E', '#EE7B91', '#E85285', '#BE408C', '#BE408C'], /** 20色板 */ colors20: ['#FACDAA', '#F4A49E', '#EE7B91', '#E85285', '#BE408C', '#BE408C', '#942D93'], }); const data = [ { type: '分类一', value: 27 }, { type: '分类二', value: 25 }, { type: '分类三', value: 18 }, { type: '分类四', value: 15 }, { type: '分类五', value: 10 }, { type: '其他', value: 5 }, ]; const piePlot = new Pie('container', { appendPadding: 10, data, angleField: 'value', colorField: 'type', radius: 0.8, label: {}, interactions: [{ type: 'element-active' }], theme: 'custom-theme', }); piePlot.render();
改造如下,views文件夹下新建Pie.vue,并在路由文件index.js配置路由地址。
//src/views/Pie.vue改造前 <template> <div id="piechart"></div> </template> <script> import { Pie } from '@antv/g2plot'; export default { mounted () { const data = [ { type: '分类一', value: 27 }, { type: '分类二', value: 25 }, { type: '分类三', value: 18 }, { type: '分类四', value: 15 }, { type: '分类五', value: 10 }, { type: '其他', value: 5 }, ]; const piePlot = new Pie('piechart', { appendPadding: 10, data, angleField: 'value', colorField: 'type', radius: 0.8, label: {}, interactions: [{ type: 'element-active' }], }); piePlot.render(); } } </script>
改造前效果:
在上述代码中添加新的theme主题颜色配置:colors10: [‘blue’, ‘red’, ‘yellow’, ‘lightgreen’, ‘lightblue’, ‘pink’],//src/views/Pie.vue改造后 <template> <div id="piechart"></div> </template> <script> import { Pie } from '@antv/g2plot'; export default { mounted () { const data = [ { type: '分类一', value: 27 }, { type: '分类二', value: 25 }, { type: '分类三', value: 18 }, { type: '分类四', value: 15 }, { type: '分类五', value: 10 }, { type: '其他', value: 5 }, ]; const piePlot = new Pie('piechart', { appendPadding: 10, data, angleField: 'value', colorField: 'type', radius: 0.8, label: {}, interactions: [{ type: 'element-active' }], theme: { colors10: ['blue', 'red', 'yellow', 'lightgreen', 'lightblue', 'pink'], }, }); piePlot.render(); } } </script>
改造后效果:
讨论
关于dark主题的参数设置,在g2plot源码中未找到,如有知晓的同学还请在评论中留言告知。自定义机制中使用registerTheme未能成功,但是在g2plot-v2-beta中使用line.chart.theme(‘dark’);成功切换暗黑主题,详见
https://g2plot-v2-beta.antv.vision/zh/examples/line/basic#line插入line.chart.theme('dark');
如本文对您有帮助,欢迎点赞或评论😄!!!
参考资料
https://www.yuque.com/antv/g2-docs/tutorial-theme (语雀AntV/G2 文档)
https://www.yuque.com/antv/g2plot/zok1sq (G2Plot 2.0 规划)
https://zhuanlan.zhihu.com/p/60812943 (知乎antv 修改主题 背景色)
https://github.com/antvis/G2Plot/issues/1226
https://github.com/antvis/G2Plot/issues/444
https://github.com/antvis/G2Plot/issues/1199
https://github.com/antvis/G2Plot/pull/1143/commits/9085d4fd6a7f92de3c1c83cb73314d590a24a067
https://g2.antv.vision/en/docs/manual/developer/registertheme
https://github.com/antvis/G2Plot/pull/1143
https://github.com/antvis/G2Plot/issues/1546
https://github.com/antvis/G2Plot/pull/1143/files/5c88e2c1ae414a9e20abe5c217c8bbeabbca11fb -
G2Plot自定义tooltip的title
2021-12-21 16:50:28官网链接:https://g2plot.antv.vision/zh/examples/bar/basic#width-ratio 效果如下 默认显示如下: tooltip默认展示的title是我们Y轴对应数据, 默认展示的g2-tooltip-list-item是x轴数据类型名称:x轴对应的数据... -
antv | G2Plot 数据可视化图表库-案例
2021-11-02 15:33:30G2Plot开箱即用的图表库 定义图表插件 ChartDiscount.vue <template> <div id="ChartDiscount" ref="ChartDiscount"></div> </template> <script> import { Line } from '@... -
G2Plot Tooltip 自定义头部、尾部、辅助线
2022-01-04 11:49:51<template> <!-- 图表 --> <div id="Line1">...import { Line } from '@antv/g2plot' export default { mounted () { // 数据源 const dataSource = [ { title: '1998年5月', . -
G2Plot 图例(legend)带瞄准图标解决
2022-01-24 10:05:15本地使用没有该图标,线上服务器有显示该图标,发现是线上、线下版本不一样导致的,线上是新版本,本地是老版本,新版本新加的功能,如果不需要可以通过属性隐藏。 -
AntV | G2Plot
2021-02-08 11:39:30g2plot简介 g2plot是一套简单、易用、并具备一定扩展能力和组合能力的统计图表库,基于图形语法理论搭建而成,"g2plot"中的 g2 即意指图形语法 (the Gramma of Graphics),同时也致敬了 ggplot2。 官方文档:... -
antd使用g2plot统计图表(7)
2022-04-29 16:38:26G2Plot 是一套简单、易用、并具备一定扩展能力和组合能力的统计图表库,基于图形语法理论搭建而成。 特性 开箱即用、默认好用的高质量统计图表 提炼自企业级产品的视觉语言和设计规范 响应式图表:致力于解决图表... -
G2plot图表在Vue中使用-获取新数据后二次渲染图表-案例
2022-06-22 13:47:38效果 示例代码-api介绍 import { Line } from '@antv/g2plot'; function getData() { // generate an array of random data const data = []; const time = new Date().getTime(); for (let i = -19; i ; i += 1) { ... -
antv g2plot可视化图表在vue中的使用之一:环境搭建
2020-09-18 10:48:31简介 g2plot 是一套简单、易用、并具备一定扩展能力和组合能力的统计图表库,基于图形语法理论搭建而成,"g2plot"中的 g2 即意指图形语法 (the Gramma of Graphics),同时也致敬了 ggplot2。 ... -
G2Plot(antV)柱状图demo
2022-05-20 17:58:34G2Plot(antV)柱状图简单修改xy轴、标题等样式的demo -
antv g2plot可视化图表在vue中的使用之二:绘制折线图条形图柱状图
2020-09-21 10:27:45需要注意使用vue create创建时选择手动方式"Mannually select features",具体可参照《NodeJs+Vue+Element UI+Antd+Antv全栈开发可视化后台管理系统之一:搭建前端框架》《antv g2plot可视化图表在vue中的使用之一:... -
【Tips】AntV G2Plot笔记
2022-03-11 14:16:23陆续记载在使用AntV G2Plot过程中的一些小tips。 1、传入数据时一定要注意作为x、y轴的条目必须具有唯一性;如下数据中,要用name作为x轴条目,映射后会造成图表重叠的情况; 我的解决方法是:传入数据时将name和... -
教你使用 G2Plot 绘制星空诺贝尔奖可视化
2020-12-30 15:26:21语雀作品介绍本次要分享的是使用 G2Plot 来实现「财新网」 诺贝尔奖可视化作品,原作品地址。本次对该作品进行了部分简化和改造,下文先介绍下具体的视觉设计和视觉元素对应的含义,再给大家介绍下实现该作品的一个... -
使用 AntV/G2/G2Plot 如何优化图表体验
2020-12-10 10:19:39G2Plot v2 版本,从今年 8 月开始开发,目前差不多已经快 4 个月了,达成:25+ 常用的统计图表80% 图表在复杂 BI,LowCode 产品中使用验证97% 代码单测覆盖率5+ 积极的社区同学参数在 v2 版本中,我们把通用的体验优... -
FORMILY+AntV | G2plot 实现图表设置
2022-07-05 13:34:54拿项目中上面的折线图举例, 在网址:基础折线图 | G2Plot 可以将图右侧的图形样式,拿到图下方的JavaScript中去测试,观察图上方的图形有什么变化,如果放上去有自己想要的效果,可以在FORMILY如下图网址为... -
antv-g2plot
2021-02-06 12:57:17G2Plot基于图形语法(the Grammar of Graphics)的图表库。一套简单、易用、并具备一定扩展能力和组合能力的统计图表库,基于图形语法理论搭建而成,『G2Plot』中的 G2 即意指图形语法 (the Grammar of Graphics),... -
[vue]vue接入AntV G2Plot
2022-04-01 20:01:09npm install @antv/g2plot --save 配置 在main.js中 引入 import g2 from '@antv/g2plot' Vue.prototype.$G2 = g2 使用 图表地址:https://g2plot.antv.vision/zh/examples/line/multiple#style-callback <... -
AntV/G2Plot 开源 - 精雕细琢,打造极致可视化图表体验
2020-12-19 02:51:52我们目前所在的产品是 DeepInsight,主要负责 DeepInsight 跟可视化相关的问题,为了解决 DeepInsight 在可视化体验上的一些问题,我们深度参入了 G2 整个技术栈的开发。背景DeepInsight 是一个数据分析和洞察工具,... -
G2plot 面积图Area更新空数据,页面渲染不彻底
2022-06-28 17:46:16G2plot渲染空数组,页面更新不彻底,要先销毁图表再初始化一次 -
vue2 使用AntV 以g2plot为例
2022-04-25 10:11:50npm install @antv/g2plot 代码: <template> <div id="app"> <div id="container"></div> </div> </template> <script> import { Bar } from '@antv/g2plot';... -
G2Plot自定义悬浮提示(tooltip)
2022-07-01 15:22:51G2Plot自定义悬浮提示(tooltip) -
antv g2plot可视化图表在vue中的使用之四:为图表添加事件
2020-10-16 16:46:25文章目录图表事件g2plot升级 图表事件 对图表进行个性化设置,包含 基本的折线图的配置可参考g2plot官网教程 (https://g2plot.antv.vision/zh/docs/manual/getting-started)不再赘述。 下面以柱状图为例,也可在...