G2图使用-创建简单的柱状图

g2plot 是一套简单、易用、并具备一定扩展能力和组合能力的统计图表库,基于图形语法理论搭建而成,"g2plot"中的 g2 即意指图形语法 (the Gramma of Graphics),同时也致敬了 ggplot2。

下面是一个简单的是用例子

<template>
    <div ref="chartRef"></div>
</template>

<script setup>
import { onMounted, ref, defineProps, toRefs } from 'vue';
import { Chart } from '@antv/g2';

const props = defineProps({ config: Object })
const { config } = toRefs(props)

const chartRef = ref();

const initChart = () => {
  const chart = new Chart({
    ...config.value,
    container: chartRef.value,
    autoFit: true,
    forceFit: true,
  })
  chart
    // .theme({ type: 'classicDark' })
    .title({
      title: `${window.CONFIG.systemName}分析`,
      // subtitle: 'world',
    })
    .interval()
    .data({
      type: 'fetch',
      value: '/api/hdfs/read-csv?path=/output/hdfsJobByMonth/part-r-00000',
      format: 'csv',
      // 如果是csv文件,则自动判断数据类型
      autoType: true,
      transform: [
        // {
        //   type: 'log'
        // },
        {
          type: 'map',
          callback: (val) => { val['年月'] = val['时间'] + '月'; return val; },
        },
        {
          type: 'sortBy',
          fields: ['时间'], // 根据 sold 字段排序
        },
        // fold 这是生成一个key value 的map
        {
          type: 'fold',
          fields: window.CONFIG.dataHeader,
          key: window.CONFIG.chartX,
          value: window.CONFIG.chartY,
        },
      ],

    })
    .encode('x', '年月')
    .encode('y', window.CONFIG.chartY)
    // dodgeX 生成 series 通道值为 color 通道的值,根据 series 通道实现分组效果
    .transform({ type: 'dodgeX' })
    // 根据 window.CONFIG.chartX 颜色进行区分,如果不加,则显示全部数据颜色固定
    .encode('color', window.CONFIG.chartX)

    // .encode('shape', 'hv')

    // .scale('x', {
    //     range: [0, 1],
    // })
    // .scale('y', {
    //     nice: true,
    // })
    // .axis('x', { title: null, line: true, tick: true })
    // .axis('y', { 
    //   title: null, 
    //   line: true, 
    // })

    // chart.line()
    // // chart.line().encode('shape', 'smooth');

    // chart.point().encode('shape', 'point').tooltip(false);


  chart.render();
  return chart;
}

onMounted(() => {
  console.log(chartRef.value)
  initChart()
})

</script>

<style lang="scss" scoped>

</style>

其中需要注意的是: .encode(‘color’, window.CONFIG.chartX) 用来实现的是图例,图例的内容为 window.CONFIG.chartX ,其中color 可以进行变化

因为 prop 接受了主题的配置,所有的颜色都会根据主题的index.js进行变化


另外 fetch 通过拉取 hdfs 中算好的 csv 文件来获得值,里面的 transform 对值进行转换,其中 type fold 能生成一个 key value 的map

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值