Plotting with Vega-Lite in Nextjournal

Nextjournal now fully supports displaying Vega-Lite plots in your notebooks. Any valid Vega-Lite grammar that’s written as JSON to /results can be displayed using Nextjournal’s results viewer.

If your result has a .vl.json file extension, Nextjournal will automatically select the vega-lite viewer to display the plot. Here is a simple Bash code cell rendering an example from the Vega-Lite docs:

echo '{
  "width": 500, "height": 300,
  "data": {"url": "https://vega.github.io/vega-datasets/data/unemployment-across-industries.json"},
  "mark": "area",
  "encoding": {
    "x": {
      "timeUnit": "yearmonth", "field": "date", "type": "temporal",
      "axis": {"domain": false, "format": "%Y", "tickSize": 0}
    },
    "y": {
      "aggregate": "sum", "field": "count","type": "quantitative",
      "axis": null,
      "stack": "center"
    },
    "color": {
    	"field":"series",
      "type":"nominal",
      "scale":{"scheme": "category20b"}
    }
  }
}' > /results/plot.vl.json
0.2s
Bash

When not using the .vl.json extension, the vega-lite viewer can also be selected from the viewers selector on the left-hand side for any JSON result:

Using Altair and Vega-Lite in Python

While you can always select the viewer (or set the extension) manually, there’s also full support for the Altair package in Python. Altair is a wrapper around Vega-Lite that makes working with statistical visualization in Python very simple. Just install and import the altair package and return a plot to display it.

Here is an example using altair to plot temperature predication data in various scenarios for the Chicago area based on a subset of the OpenNEX DCP30 dataset:

OpenNEX-chicago-climate.csv
pip install altair
3.4s
Bash in Python
import pandas as pd
import altair as alt
# Read in the CSV
data = pd.read_csv(
OpenNEX-chicago-climate.csv
)
# Specify categorical data
for col in ['Model', 'Scenario', 'Variable']:
    data[col] = data[col].astype('category')
# Coax date strings to beginning of year dates
data['Year'] = data['Date'] \
	.astype('datetime64') \
	.map(lambda d: "%d-01-01" % d.year) \
	.astype('datetime64')
# Convert temperatures from Kelvin to Celsius
data['Temperature'] = data['Value'] - 273.15
# Plot maximum temperature by year
model = data.loc[1, 'Model']
title = 'Maximum mean temperature for warmest month using model %s' % model
# Allow plotting large datasets
alt.data_transformers.disable_max_rows()
# Return the plot
alt.Chart(data, title=title).mark_line().encode(
  x='Year:T',
  y=alt.Y('max_temp:Q',
       title='Temperature [Celsius]',
       scale=alt.Scale(
         domain=(25, 40),
         clamp=True
       )
  ),
  color='Scenario'
).transform_aggregate(
	max_temp='max(Temperature)',
  groupby=['Year', 'Scenario']
)
11.8s
Python

Displaying Vega-Lite Plots in Clojure

In Clojure, you can return your Vega-Lite grammar directly as EDN and set the ^{:nextjournal/viewer "vega-lite"} metadata. This tells Nextjournal to interpret the grammar as JSON and show it using the vega-lite viewer:

^{:nextjournal/viewer :vega-lite}
{:width 650
 :height 400
 :data
 {:url "https://vega.github.io/vega-datasets/data/us-10m.json"
  :format
  {:type "topojson" :feature "counties"}}
 :transform
 [{:lookup "id"
   :from
   {:data {:url "https://vega.github.io/vega-datasets/data/unemployment.tsv"}
    :key "id"
    :fields ["rate"]}}]
 :projection {:type "albersUsa"}
 :mark "geoshape"
 :encoding
 {:color {:field "rate" :type "quantitative"}}}
0.2s
Clojure

Plotting with VegaLite in Julia

Plotting with VegaLite is easy enough with the VegaLite.jl package and Nextjournal's VegaLite image, that has everything installed:

using VegaLite, VegaDatasets
p = dataset("cars") |>
@vlplot(
    :point,
    x = :Horsepower,
    y = :Miles_per_Gallon,
    color = :Origin,
    width = 650,
    height = 400
) |> VegaLite.interactive()
20.0s
Julia

You can find more examples in the image article or in the VegaLite.jl documentation.

Runtimes (4)