Skip to content

Instantly share code, notes, and snippets.

@bmitc
Created April 2, 2023 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmitc/d5054c88e6be9bbdc9907c045b57406e to your computer and use it in GitHub Desktop.
Save bmitc/d5054c88e6be9bbdc9907c045b57406e to your computer and use it in GitHub Desktop.
VegaLite animation

Animating a VegaLite chart

Mix.install([:vega_lite, :kino_vega_lite, :jason])
Resolving Hex dependencies...
Resolution completed in 0.047s
New:
  jason 1.4.0
  kino 0.9.0
  kino_vega_lite 0.1.8
  table 0.1.2
  vega_lite 0.1.7
* Getting vega_lite (Hex package)
* Getting kino_vega_lite (Hex package)
* Getting jason (Hex package)
* Getting kino (Hex package)
* Getting table (Hex package)
==> table
Compiling 5 files (.ex)
Generated table app
==> vega_lite
Compiling 5 files (.ex)
Generated vega_lite app
==> kino
Compiling 39 files (.ex)
Generated kino app
==> kino_vega_lite
Compiling 4 files (.ex)
Generated kino_vega_lite app
==> jason
Compiling 10 files (.ex)
Generated jason app
:ok

Section

alias VegaLite, as: Vl
VegaLite
chart = fn ->
  data =
    for month <- [
          "Jan",
          "Feb",
          "Mar",
          "Apr",
          "May",
          "Jun",
          "Jul",
          "Aug",
          "Sep",
          "Oct",
          "Nov",
          "Dec"
        ] do
      for day <- 1..31 do
        %{month: month, day: day, temperature: Enum.random(32..100)}
      end
    end
    |> List.flatten()

  Vl.new(title: "Daily max temperatures")
  |> Vl.data_from_values(data)
  |> Vl.mark(:rect)
  |> Vl.encode_field(:x, "day", type: :ordinal, title: "Day")
  |> Vl.encode_field(:y, "month", type: :ordinal, title: "Month")
  |> Vl.encode_field(:color, "temperature",
    aggregate: :max,
    type: :quantitative,
    legend: [title: nil]
  )
end
#Function<43.3316493/0 in :erl_eval.expr/6>
Stream.interval(500)
|> Stream.take(10)
|> Kino.animate(nil, fn _, _ ->
  display = chart.()
  {:cont, display, nil}
end)
Stream.interval(100)
|> Stream.take(100)
|> Kino.animate(nil, fn _, _ ->
  display =
    chart.()
    |> Vl.Export.to_svg()
    |> Kino.Image.new(:svg)

  {:cont, display, nil}
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment