David Schmudde / Aug 08 2019

Vega in Clojure

Interactive Example

0.7s
Clojure
^{:nextjournal/viewer "vega-lite"}
{
  "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}
    ]
  },
  "selection" {
    "highlight" {"type" "single", "empty" "none", "on" "mouseover"},
    "select" {"type" "multi"}
  },
  "mark" {
    "type" "bar",
    "fill" "#4C78A8",
    "stroke" "black",
    "cursor" "pointer"
  },
  "encoding" {
    "x" {"field" "a", "type" "ordinal"},
    "y" {"field" "b", "type" "quantitative"},
    "fillOpacity" {
      "condition" {"selection" "select", "value" 1},
      "value" 0.3
    },
    "strokeWidth" {
      "condition" [
        {
          "test" {
            "and" [
              {"selection" "select"},
              "length(data(\"select_store\"))"
            ]
          },
          "value" 2
        },
        {"selection" "highlight", "value" 1}
      ],
      "value" 0
    }
  },
  "config" {
    "scale" {
      "bandPaddingInner" 0.2
    }
  }
}

Static Examples

(defn plot [spec] (with-meta spec {:nextjournal/viewer "vega-lite"}))

(defn play-data [& names]
  (for [n names
        i (range 20)]
    {:time i :item n :quantity (+ (Math/pow (* i (count n)) 0.8) 
                                  (rand-int (count n)))}))
(def line-plot
  {:data {:values (play-data "monkey" "slipper" "broom")}
   :encoding {:x     {:field "time"}
              :y     {:field "quantity"}
              :color {:field "item" :type "nominal"}}
   :mark "line"})
'user/line-plot
(plot line-plot)
import altair as alt
import pandas as pd

source = pd.DataFrame({
    'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
    'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})

alt.Chart(source).mark_bar().encode(
    x='a',
    y='b'
)
pip install altair