Antv G2折线图+柱状图 自定义图例(legend)和tooltip

在这里插入图片描述

自定义图例: 这个可能实现的思路不太对, 目前是在数据列表里新建了个无用字段,在坐标轴隐藏该字段,通过color触发图例,再通过legend自定义内容
找这些东西太难了,找半天找不到,不用color的情况下我用legend无效

import React, { useState, useEffect, useRef} from "react";
import "./chart.less"
import { Chart } from "@antv/g2";

const Charts = () => {

    const chartRef = useRef()
    const data = [
        { name: "杭州银行", score: 2, num: 5, city: "bj" },
        { name: "南京银行", score: 4, num: 11, city: "bj" },
        { name: "江西邮储", score: 8, num: 13, city: "bj" },
        { name: "农业银行", score: 5, num: 9, city: "bj" },
        { name: "工商银行", score: 9, num: 6, city: "bj" },
        { name: "人民银行", score: 3, num: 29, city: "bj" },
    ]

    const [chart, setChart] = useState(null)

    useEffect(() => {
        if (data && !chart) {
            const c = new Chart({
                container: 'c7',
                autoFit: true,
                width: 500,
                height: 300,
            });
            setChart(c)
        }
    }, [data])

    useEffect(() => {
        chart && renderChart()
    }, [chart, data])

    const renderChart = () => {
        const nums = data.map(i => i.num)
        const maxValue = Math.max(...nums)
        const max = Math.ceil(maxValue / 10) * 10
        const margin = 1 / 5

        chart.clear()
        chart.data(data);

        chart.scale('score', { // 右侧坐标轴
            min: 0,
            max: 10,
            tickCount: 6, // 左右坐标轴刻度数量保持一致 好看点
            range: [0, 1 - margin / 2],
        })

        const tick = max / 5
        let ticks = new Array(6).fill(null)
        ticks = ticks.map((i, t) => t * tick)
        chart.scale('num', { // 左侧坐标轴
            min: 0,
            max: max,
            ticks: ticks,
            tickCount: 6,
            range: [0, 1 - margin / 2],
        })

        chart.scale('city', { // 无用坐标轴
            min: 0,
            max: max,
            ticks: ticks,
            tickCount: 6,
            range: [0, 1 - margin / 2],
        })

        chart.scale('name', {
            nice: true,
        })

        chart.axis("city", { // 隐藏无用坐标轴内容
            label: {
                formatter: () => ""
            }
        })

        chart.axis("num", {
            title: {
                text: "单位: 个",
                autoRotate: false,
                position: "end",
                offset: -10,
                textStyle: {
                    textAlign: 'start', // 文本对齐方向,可取值为: start middle end
                    fontSize: '12', // 文本大小
                    fontWeight: 'bold', // 文本粗细
                    textBaseline: 'top' // 文本基准线,可取 top middle bottom,默认为middle
                },
            },
        })

        chart.axis("score", {
            title: {
                text: "单位: 分",
                autoRotate: false,
                position: "end",
                offset: -10,
                textStyle: {
                    textAlign: 'start', // 文本对齐方向,可取值为: start middle end
                    fontSize: '12', // 文本大小
                    fontWeight: 'bold', // 文本粗细
                    textBaseline: 'top' // 文本基准线,可取 top middle bottom,默认为middle
                },
            },
        })

        chart.axis("name", {
            label: {
                autoRotate: true,
                autoHide: false
            },
        })

        chart.interaction('active-region');
		// 柱状图设置
        chart
            .interval()
            .label("num", {
                offset: -10
            })
            .size(36)
            .position('name*num')
            .tooltip('num*score', (num, score) => {
                return {
                    num,
                    score
                }
            })
            .color("city")
		// 折线图设置 隐藏无用的字段
        chart.
            line()
            .position('city')
            .style({
                stroke: "transparent"
            })
        // 关闭图例点击事件 没找到api  没实现   点击图例可以触发这个方法
        // chart.on('legend:click', ev => {
        //     return false
        // });
        // 修改 自定义图例 增加 custom: true
        chart.legend({
	      custom: true,
	      position: "bottom",
	      flipPage: false,
	      items: [
	        {
	          name: "项目",
	          marker: {
	            symbol: "square",
	            style:{
	              fill: "#6395f9"
	            },
	            clickable: false
	          },
	        },
	        {
	          name: "评分",
	          marker: {
	            symbol: "circle",
	            style:{
	              fill: "#f59a23"
	            },
	            clickable: false
	          },
	        }
	      ]
	    })        

		// tooltip的自定义内容
        const itemTpl = `
            <div class='chart7Tpl'>
                <div class='tpl'>
                    <span class="tpl1">·</span>
                    评分:&nbsp;&nbsp;&nbsp;{score} 分
                </div>
                <div class='tpl'>
                    <span class="tpl2">·</span>
                    项目:&nbsp;&nbsp;&nbsp;{num} 个
                </div>
            </div>
        `

        chart.tooltip({
            showTitle: true,
            showMarkers: false,
            itemTpl: itemTpl
        });
		// 设置折线内容 颜色
        chart
            .line()
            .position('name*score')
            .size(4)
            .color("", () => "#f59a23")
            .tooltip('num*score', (num, score) => {
                return {
                    num,
                    score
                }
            })
   	    chart.removeInteraction('legend-filter'); // 自定义图例,移除默认的分类图例筛选交互
        chart.render();
    }

    return (
        <div className={"chart7"}>
            <div id="c7" ref={chartRef} />
        </div>
    )
}

export default Charts;

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
AntV G2 是一款基于图形语法的可视化图表库,支持绘制多种类型的图表,包括柱状图折线图等。要绘制分组柱状图折线图混合的图表,可以使用 G2 的 ComboChart 组件。 首先,需要定义数据源,并指定数据字段的类型(例如 x 轴、y 轴等)。接着,可以使用 ComboChart 组件来绘制混合的图表。在 ComboChart 中,可以分别指定柱状图折线图的样式、颜色等属性,如下所示: ```javascript import { Chart } from '@antv/g2'; const data = [ { year: '2010', sales: 450, profit: 200 }, { year: '2011', sales: 560, profit: 230 }, { year: '2012', sales: 620, profit: 250 }, { year: '2013', sales: 750, profit: 300 }, { year: '2014', sales: 800, profit: 350 }, ]; const chart = new Chart({ container: 'container', autoFit: true, height: 400, }); chart.data(data); chart.scale({ sales: { min: 0, }, profit: { min: 0, }, }); chart.axis('year', { label: { style: { fill: '#aaaaaa', }, }, }); chart.line().position('year*profit').color('#fdae6b'); chart.interval().position('year*sales').color('#2c7bb6'); chart.render(); ``` 在上面的代码中,我们定义了一个数据源,并指定了 x 轴和 y 轴的数据字段。接着,创建一个 Chart 实例,并指定容器,然后设置数据源和坐标轴的样式。最后,使用 line() 和 interval() 方法分别绘制折线图柱状图,并指定它们的位置和颜色。 需要注意的是,ComboChart 支持多种混合图表类型,包括折线图柱状图、面积图等,可以根据自己的需求选择适合的图表类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值