Introducing altair

An R interface to the Altair Python Package

Ian Lyttle
2018-05-20

Introducing altair, an R package to work with the Python package Altair, which you can use to build and render Vega-Lite chart-specifications:

https://vegawidget.github.io/altair

Vega-Lite offers an implementation of an interactive grammar of graphics. The vocabulary and syntax of this grammar is different from that used by ggplot2. However, the fundamental ideas are very much the same: ggplot2 offers aesthetics, geoms, and scales; Vega-Lite offers marks, encondings, and scales. Vega-Lite also offers interactivity “baked into” the rendering.

Demonstration

Following this Altair example, here’s a set of scatterplots with linked brushing. You can click-and-drag to select observations in one chart, and they are highlighted in the other:

Code

library("altair")
vega_data <- import_vega_data()
brush <- alt$selection_interval()
chart_mpg <-
  alt$Chart()$
  mark_point()$
  encode(
    x = "Horsepower:Q",
    y = "Miles_per_Gallon:Q",
    color = alt$condition(brush, "Origin:N", alt$value("lightgray"))
  )$
  properties(selection = brush, width = 250, height = 250) 
chart_disp <- 
  chart_mpg$encode(
    x = "Displacement:Q"
  )
chart <- 
  (chart_mpg | chart_disp)$
  properties(
    data = r_to_py(vega_data$cars()),
    title = "Linked-Brush Scatterplot"
  )

The interactivity is a fundamental part of Vega-Lite; a interactive chart is rendered and controlled entirely in your broswer.

Resources

You may be initially interested in the installation instructions, as your biggest hassle may be getting your Python environment set up.

You may also be interested in a first example, an interactive example, and the interactive section of the gallery.

Acknowledgements

This approach is distinct from efforts to build a native R interface to Vega-Lite, by Bob Rudis and coworkers: the vegalite package, which has inspired this effort.

This package rests on foundations provided by reticulate and Altair. Jake Vanderplas has been super supportive and patient in answering Altair questions, which is greatly appreciated.

It is a lot of fun to work with these folks on this project; this package would not exist without their efforts:

Citation

For attribution, please cite this work as

Lyttle (2018, May 20). vegawidget: Introducing altair. Retrieved from https://vegawidget.rbind.io/posts/2018-05-20-introducing-altair/

BibTeX citation

@misc{lyttle2018introducing,
  author = {Lyttle, Ian},
  title = {vegawidget: Introducing altair},
  url = {https://vegawidget.rbind.io/posts/2018-05-20-introducing-altair/},
  year = {2018}
}