Skip to content

Instantly share code, notes, and snippets.

@dharasim
Last active Dec 12, 2018
Embed
What would you like to do?
VegaLite plots in Julia
df = DataFrame(x=randn(500), y= randn(500))
df |> vlplot(
mark = :point,
encoding = (
x = (field=:x, typ=:quantitative),
y = (field=:y, typ=:quantitative)
)
)
using DataFrames, CSV, JSON
function named_tuples(df::AbstractDataFrame)
M = Matrix(df)
NT = NamedTuple{tuple(names(df)...), Tuple{eltypes(df)...}}
map(1:size(M, 1)) do i
NT(M[i,:])
end
end
JSON.print(io::IO, df::AbstractDataFrame) = print(io, json(named_tuples(df)))
function vl2svg(vlspec::AbstractString)
tmp_vlspec, tmp_svg = tempname(), tempname()
write(tmp_vlspec, vlspec)
run(pipeline(`vl2svg`, stdin=tmp_vlspec, stdout=tmp_svg))
svg = read(tmp_svg, String)
rm(tmp_vlspec); rm(tmp_svg)
svg
end
function vlspec(spec::NamedTuple=NamedTuple{(),Tuple{}}(()); args...)
function (df)
with_data = (spec..., values(args)..., data=(values=JSONText(json(df)),))
replace(json(with_data), "typ"=>"type")
end
end
vlplot(spec::AbstractString) = display("image/svg+xml", vl2svg(spec))
vlplot(spec::NamedTuple=NamedTuple{(),Tuple{}}(()); args...) = df -> vlplot(vlspec(spec; args...)(df))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment