jakevdp
jakevdp

Reputation: 86330

How to apply a vega theme when using vl2png

I have a vega-lite chart specification that I'd like to save to PNG, using one of the themes available in vega-themes.

With vega-embed, I can use a script like the following to produce a themed chart in the browser, and manually click "Save to PNG" in the menu:

<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
  <script src="https://cdn.jsdelivr.net/npm/vega-lite@4"></script>
  <script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
</head>
<body>

<div id="vis"></div>

<script type="text/javascript">
  var spec = {
    "$schema": "https://vega.github.io/schema/vega-lite/v4.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"}
    }
  };
  vegaEmbed("#vis", spec, {theme: 'fivethirtyeight'});
</script>
</body>
</html>

enter image description here

Alternatively, I can automatically create an un-themed png using the vl2png command-line tool from vega-cli:

$ cat spec.json | vl2png > chart.png

enter image description here

But I am unsure of where to specify the theme within the vl2png command.

How can I specify a chart theme when using the vega-cli to render and save a chart?

Upvotes: 1

Views: 612

Answers (1)

marcprux
marcprux

Reputation: 10355

vega-themes aren't available from the vega-cli utilities – they are instead embedded in vega-embed. The good news is that since themes are merely vega config objects, you can just manually include one of them in the spec (on the command-line you can use a utility like jq to merge multiple JSON files).

The bad news, however, is that while the Typescript source for generating the theme objects is available, the vega-themes project doesn't appear to export any of the raw JSON config objects for the themes themselves. So you need to generate it yourself. If you have the vega-theme repo checked out and built, you could extract a config object like this:

cat vega-themes/build/theme-excel.js | sed 's/export default \(.*\);/console.log(JSON.stringify({config: \1}));/g' | node

So putting it all together, you can apply a theme from the console using this bit of gnarly code:

(cat vega-lite/examples/specs/bar.vl.json; \
 cat vega-themes/build/theme-dark.js \
  | sed 's/export default \(.*\);/console.log(JSON.stringify({config: \1}));/g' \
  | node)  \
  | jq -s add \
  | vl2png > spec_dark.png

Upvotes: 2

Related Questions