How to create a Vega chart?

The boilerplate for a Vega chart is around 20 lines. It involves fetching the chart specification from a remote URL, render the chart.

Import dependencies

Import Vega library

            
<script src="https://unpkg.com/vega"></script>


Create a chart container

Vega chart will be added here

            
<div class="chart"></div>


Vega specification

Fetch Vega specification from a URL

            
var _spec = "https://gist.githubusercontent.com/bkamapantula/677c0aee77115c60eda89e9d979525fc/raw/1ba3cb9790cc05763b8ec8fb1a85f7791efaa609/boxplot.json"
var el = document.getElementsByClassName('chart')[0]
fetch(_spec)
  .then(res => res.json())
  .then(spec => render_vega(spec, el))
  .catch(err => console.error(err))


Render the Chart

Draw the chart using spec variable

            
function render_vega(spec, el) {
  new vega.View(vega.parse(spec))
    .renderer("svg")
    .logLevel(vega.Warn)
    .initialize(el)
    .hover()
    .run()
}


Complete code

Putting it all together. Copy the code in a HTML page and run it. Integration docs

            
<div class="chart"></div>
<script src="https://unpkg.com/vega"></script>
<script>
var _spec = "https://gist.githubusercontent.com/bkamapantula/677c0aee77115c60eda89e9d979525fc/raw/1ba3cb9790cc05763b8ec8fb1a85f7791efaa609/boxplot.json"
var el = document.getElementsByClassName('chart')[0]

function render_vega(spec, el) {
  new vega.View(vega.parse(spec))
    .renderer("svg")
    .logLevel(vega.Warn)
    .initialize(el)
    .hover()
    .run()
}

fetch(_spec)
  .then(res => res.json())
  .then(spec => render_vega(spec, el))
  .catch(err => console.error(err))
</script>


Similarly, one can create Vega-Lite chart. Check the example block.

References

  1. Axes & Legends in Vega, Vega Observable
  2. Vega Editor, Vega examples with live editing
  3. Vega Viewer, VSCode Extension