官网: https://vega.github.io/vega/
Bar Chart
开始分析此条形图的 Vega 定义
{
"$schema": "https://vega.github.io/schema/vega/v3.json",
"width": 400,
"height": 200,
"padding": 5,
"data": [
{
"name": "table",
"values": [
{"category": "A", "amount": 28},
{"category": "B", "amount": 55},
{"category": "C", "amount": 43},
{"category": "D", "amount": 91},
{"category": "E", "amount": 81},
{"category": "F", "amount": 53},
{"category": "G", "amount": 19},
{"category": "H", "amount": 87}
]
}
],
"signals": [
{
"name": "tooltip",
"value": {},
"on": [
{"events": "rect:mouseover", "update": "datum"},
{"events": "rect:mouseout", "update": "{}"}
]
}
],
"scales": [
{
"name": "xscale",
"type": "band",
"domain": {"data": "table", "field": "category"},
"range": "width",
"padding": 0.05,
"round": true
},
{
"name": "yscale",
"domain": {"data": "table", "field": "amount"},
"nice": true,
"range": "height"
}
],
"axes": [
{ "orient": "bottom", "scale": "xscale" },
{ "orient": "left", "scale": "yscale" }
],
"marks": [
{
"type": "rect",
"from": {"data":"table"},
"encode": {
"enter": {
"x": {"scale": "xscale", "field": "category"},
"width": {"scale": "xscale", "band": 1},
"y": {"scale": "yscale", "field": "amount"},
"y2": {"scale": "yscale", "value": 0}
},
"update": {
"fill": {"value": "steelblue"}
},
"hover": {
"fill": {"value": "red"}
}
}
},
{
"type": "text",
"encode": {
"enter": {
"align": {"value": "center"},
"baseline": {"value": "bottom"},
"fill": {"value": "#333"}
},
"update": {
"x": {"scale": "xscale", "signal": "tooltip.category", "band": 0.5},
"y": {"scale": "yscale", "signal": "tooltip.amount", "offset": -2},
"text": {"signal": "tooltip.amount"},
"fillOpacity": [
{"test": "datum === tooltip", "value": 0},
{"value": 1}
]
}
}
}
]
}
schema
图解;计划;概要
category
种类
amount
数量
signals
信号
tooltip
工具提示;提示信息
datum
数据,资料
scales
天平;缩放
domain
领域;域名;产业
field
字段;领域;足球场
range
范围;幅度;山脉
round
圆
nice
adj. 精密的;美好的;细微的
axes
坐标轴;轴线
marks
标记;分数
band
带,环;波段
stellblue
刚蓝色
align
对齐;排列
baseline
基线
单文件 Bar Chart 例子
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vega@4.0.0-rc.1"></script>
<script type="text/javascript">
var view;
vega.loader()
.load('https://vega.github.io/vega/examples/bar-chart.vg.json')
.then(function(data) { render(JSON.parse(data)); });
function render(spec) {
view = new vega.View(vega.parse(spec))
.renderer('canvas')
.initialize('#view')
.hover()
.run();
}
</script>
</head>
<body>
<div id="view"></div>
</body>
</html>
前端工程 vue 项目中例子
<template>
<div id="view"></div>
</template>
<script>
important * as vega from 'vega'
export default {
data () {
return {}
},
mounted () {
vega.loader()
.load('https://vega.github.io/vega/examples/bar-chart.vg.json')
.then(function(data) {
new vega.View(vega.parse(JSON.parse(data)))
.renderer('canvas')
.initialize('#view')
.hover()
.run()
});
}
}
</script>
也可以直接读取前端工程目录中的 json 文件或者自定义 json 对象显示 vega 图像
let jsonObj = {...}
new vega.View(vega.parse(JSON.parse(jsonObj)))
.renderer('canvas')
.initialize('#view')
.hover()
.run()