Implementing a Universal Visual Vue Plugin Based on AntV G2

foreword

AntV G2 Adhere to the design values ​​of nature, certainty, sense of meaning, and growth. Different from other visualization plugins, G2 is a data-driven high-interaction visualization graph syntax, which is highly usable and extensible.

With the continuous development of business visualization, the complexity of data is increasing. It is increasingly urgent to implement a general visualization plugin. This article implements a visual Vue plugin based on G2 - p-charts.

hint: p-charts It is based on the latest version of AnV G2 v3.x, because the v3.x version documentation is relatively mature. Subsequent upgrades will follow the v4.x version.

Currently, p-charts Only p-pie (pie chart), p-bar (bar chart), p-column (column chart), and p-line-chart (line chart) are implemented. Subsequent expansion of other commonly used graphics.

case

click here

quick start

Install

npm install -S p-charts
# or
yarn add p-charts

use

// main.js
import PCharts from 'p-charts'
Vue.use(PCharts)

Example: Pie Chart (p-pie)

<template>
  <p-pie
    :data="PieJson"
    :options="options"
    ref="pieRef"
    @pie-title-click="handleTitleClick"
    @pie-label-click="handleLabelClick"
  />
</template>

<script>
import PieJson from './data/pie1.json'
export default {
  data() {
    return {
      PieJson,
      options: {
        fieldMap: {
          time: 'year',
          name: 'budgetSubject',
          // Statistical indicators, can be replaced
          value: 'budgetNum'
        },
        title: `The proportion of total revenue and total expenditure-Budget (unit: ten thousand yuan)`,
        colorList: ['#1890ff', '#37c661']
      }
    }
  },
  methods: {
    updateData() {
      this.$refs.pieRef.initData()
    },
    handleTitleClick() {
      console.log('title-click')
    },
    handleLabelClick(data) {
      console.log('label-click', data)
    }
  }
}
</script>

Implementation principle

This article starts with p-pie An example of a pie chart implementation.

Options and Data

p-charts The options and data are passed as props. The default options configuration is defined in the component.

defaultOptions: {
  // title
  title: '',
  // The properties of the chart itself: width,height, etc.
  chartProps: {
    height: 400
  },
  tooltipProps: {
    showTitle: false
  },
  // graphics radius
  radius: 0.7,
  // Graphic Color List
  colorList: [],
  // Field mapping
  fieldMap: {
    name: 'budgetSubject',
    value: 'budgetFinalNum'
  },
  // value unit
  valueUnit: 'million'
}

Combine the latest options in the mouted lifecycle

this.newOptions = { ...this.defaultOptions, ...this.options }

data conversion

data conversion using @antv/data-set For conversion, there are many conversion methods, such as: data filtering, field filtering, data processing, data sorting, obtaining subsets, data completion, data percentage, data statistics, data binning, etc. Detailed description and usage reference Transform.

This article p-charts There are two main types of data transformation: data processing and data percentage.

  • Data conversion: Data processing returns the value of the data field to 0 if the value is null or undefined.
  • Data percentage: The data percentage is converted to type percent, and the percentage of each data item is counted.
const ds = new DataSet()
const dv = ds.createView().source(data)
dv.transform({
  type: 'map',
  callback(row) {
    if (
      row[valueOp] === null ||
      row[valueOp] === undefined ||
      isNaN(row[valueOp])
    ) {
      row[valueOp] = 0
    }
    return row
  }
}).transform({
  type: 'percent',
  field: valueOp,
  dimension: nameOp,
  as: 'percent'
})

Group aggregation

because p-pie (pie chart) There is no grouping aggregation, so this time with p-column (Histogram) as an example, the case demo-column3

The grouped aggregation configuration is:

// Combining Fields (Grouping Fields)
groupField: 'name',
// Entry fields (detail fields, legend fields)
itemField: 'time',
// Field mapping
fieldMap: {
  time: 'year',
  name: 'budgetSubject',
  value: 'budgetFinalNum'
}
  • fieldMap: Mainly used for field mapping, the basic graphics mainly have three fields.

    • Timeline field time: mainly used for coordinate axes (X-axis of bar charts, Y-axis of bar charts) single item or grouping The time field here does not necessarily represent time, it may be other fields, such as departments, reference: Case demo-column3
    • Name field name: mainly used for legend or data description fields
    • Value field value: Indicates the value of which field
  • groupField: grouping field, mainly used to combine groups, such as demo-column3 Group by department field. The configuration value here is the key of the fieldMap, not the value
  • itemField: item field (legend field), field description representing the data value, such as demo-column3 Expenses for each item in the title. Again, the configuration value here is the key of the fieldMap, not the value

According to the above description, demo-column3 The configuration is as follows:

Grouping: Grouping according to the time field in the fieldMap, that is, according to the department (govDept);
The entry field is the name field in fieldMap, that is, the budget subject (subject);
The value field is: subtotal, which is the data value.

groupField: 'time',
itemField: 'name',
fieldMap: {
  time: 'govDept',
  name: 'subject',
  value: 'subtotal'
},

According to the above configuration principles, demo-column2 The configuration is as follows:

groupField: 'name',
itemField: 'time',
fieldMap: {
  time: 'outType',
  name: 'subject',
  value: 'outValue'
}

demo-bar2 Bar chart, grouped by year as follows:

fieldMap: {
  time: 'year',
  name: 'budgetSubject',
  value: 'budgetNum'
}

Data field key renamed

In order to make the legend description clearer, it is necessary to map the legend fields.

foldFields: ['subtotal', 'outBase', 'outProject'],
foldFieldsRename: {
  subtotal: 'Subtotal',
  outBase: 'basic expenses',
  outProject: 'project expenditure'
}
  • foldFields: Mainly renamed fields
  • foldFieldsRename: rename the map

Rename using The data conversion type is fold (data expansion) ,refer to p-column , configured as follows:

dv.transform({
  type: 'fold',
  fields: foldFieldsOp,
  key: this.newOptions.fieldMap[this.newOptions.itemField],
  value: valueOp
})

Case address demo-column2

Description of other options

value unit valueUnit

The value unit is mainly used for the measurement unit of the prompt information value. The default value is "10,000 yuan", "pieces" or "persons"

colorList colorList

colorList: ['#ff786b', '#0fdd7e', '#bc9dfb', '#ff2e6a', '#7effa2', '#e57ec0', '#2c818f', '#ff7730']

Graph Basic Options chartProps

The basic options for graphics are: height, width, padding, background, etc. For details, refer to the documentation Chart

chartProps: {
  height: 500,
  padding: [50, 120, 100, 120]
}

Legend configuration option legendProps

Legend configuration options are: position, title, background, etc., please refer to the documentation for details Legend legend

legendProps: {
  position: 'bottom'
}

TooltipProps configuration option tooltipProps

Legend configuration options are: showTitle, offset, itemTpl, crosshairs, etc., refer to the documentation Tooltip prompt information

tooltipProps: {
  showTitle: true
}

Data adjustment options adjustProps

Reference documentation

adjustProps: [
  {
    type: 'dodge',
    marginRatio: 1 / 32
  }
]

Graphic text configuration option labelProps

Graphical text options are configured as: offset, textStyle, etc., refer to the documentation Label graphic text

labelProps: {
  textStyle: {
    fill: '#0050b3',
    fontSize: '12',
    // fontWeight: 'bold',
    rotate: -60
  }
}

X-axis configuration options xFieldProps

The coordinate axis Axis options are configured as: title, coordinate axis line, text label, tickLine, grid grid, etc., refer to the documentation Axis coordinate axis

The default configuration is as follows:

xFieldProps: {
  label: {
    textStyle: {
      rotate: 16
    }
  }
}

Y-axis configuration options yFieldProps

Same as above, the default configuration is as follows:

yFieldProps: {
  line: {
    lineWidth: 2,
    lineDash: [3, 3]
  },
  label: {
    textStyle: {
      fill: '#aaaaaa'
    }
  },
  title: {
    offset: 60
  }
}

Data transformation configuration option transformProps

There are many types of data conversion configuration, please refer to the chapter "Data Conversion" in this article, refer to the documentation Transform data transformation

The default configuration is empty:

transformProps: []

p-map component

The p-map component is based on AntV L7 Encapsulated administrative division fill map, reference AntV L7

Currently only supports CountryLayer (China map), and will continue to improve and optimize in the future to support maps of various provinces, cities and counties

configuration options

Scene Scene configuration options chartProps

Reference documentation Scene Scene

The default configuration is as follows:

chartProps: {
  map: new Mapbox({
    center: [116.2825, 39.9],
    pitch: 0,
    style: 'blank',
    zoom: 3,
    minZoom: 0,
    maxZoom: 10
  })
}
Field mapping configuration fieldMap

Refer to the chapter "Group Aggregation" in this article. The default configuration is as follows:

fieldMap: {
  name: 'name',
  value: 'num'
},

Cooperation and exchange

Author Blog , cooperation and exchanges are welcome, and interested students are welcome to join us. submit issues.

Summarize

p-charts It is a Vue plug-in based on AntV G2, which greatly improves the efficiency of data visualization, and will continue to expand in the future.

For reprint, please indicate: my technology sharing » Implementing a Universal Visual Vue Plugin Based on AntV G2

Tags: Front-end Vue.js Visualization data visualization

Posted by smoked1 on Tue, 17 May 2022 20:16:56 +0300