如何在使用 express.js 时使用 Vega 在后端生成绘图

How to use Vega to generate plots in the backend while using express.js

https://vega.github.io/vega/usage/#node 有使用前端渲染绘图的示例 javascript。 是否可以在后端生成图并将图发送到前端? 我想我想实现这样的目标:

const vega = require('vega')
const lite = require('vega-lite')
const embed = require('vega-embed')
var yourVlSpec = {
  $schema: 'https://vega.github.io/schema/vega-lite/v2.0.json',
  description: 'A simple bar chart with embedded data.',
  data: {
    values: [
      {a: 'A', b: 28},
      {a: 'B', b: 55},
      {a: 'C', b: 43},
      {a: 'D', b: 91},
      {a: 'E', b: 81},
      {a: 'F', b: 53},
      {a: 'G', b: 19},
      {a: 'H', b: 87},
      {a: 'I', b: 52}
    ]
  },
  mark: 'bar',
  encoding: {
    x: {field: 'a', type: 'ordinal'},
    y: {field: 'b', type: 'quantitative'}
  }
};
let vegaspec = lite.compile(yourVlSpec)
var view = new vega.View(vega.parse(vegaspec), 
{renderer: 'none'})


var express = require('express');
var app = express();

app.get('/', function(req, res){
//   Can I send view directly to the front end?
//   res.send(view.toHTML());
});
app.listen(3000);

附加包: "vega-lite": "^4.0.2", "vega": "^5.9.0", "canvas": "^2.6.1"

参考https://vega.github.io/vega/usage/服务器端部署使用Node.js。

最小示例:

const vega = require('vega')
const lite = require('vega-lite')
var express = require('express');
var app = express();

var yourVlSpec = {
  $schema: 'https://vega.github.io/schema/vega-lite/v2.0.json',
  description: 'A simple bar chart with embedded data.',
  data: {
    values: [
      {a: 'A', b: 28},
      {a: 'B', b: 55},
      {a: 'C', b: 43},
      {a: 'D', b: 91},
      {a: 'E', b: 81},
      {a: 'F', b: 53},
      {a: 'G', b: 19},
      {a: 'H', b: 87},
      {a: 'I', b: 52}
    ]
  },
  mark: 'bar',
  encoding: {
    x: {field: 'a', type: 'ordinal'},
    y: {field: 'b', type: 'quantitative'}
  }
};
let vegaspec = lite.compile(yourVlSpec).spec
var view = new vega.View(vega.parse(vegaspec), 
{renderer: "none"})
view.toSVG()
  .then(function(svg) {
    app.get('/', function(req, res){
      res.send(svg);
    });
    app.listen(3000);
  })
  .catch(function(err) { console.error(err); });