Site icon R-bloggers

Cascading style sheets for R plots (via the Rcssplot package)

This post is contributed by Tomasz Konopka. Comments are welcome. tomasz@rcssplot.org

One of the great features of R is its capable graphics framework. In principle, the framework allows us to customize all aspects of the visual presentation of data.

In practice, however, customization is rather tedious. For example, R’s own boxplot function has 17 custom arguments, not counting ...stripchart has 20. Tweaking the default values for each of these arguments makes scripts quite bulky. That can be distracting from data analysis.

Several impressive frameworks already exist to help with visualization (e.g. ggplot2plot.ly, etc.) Package Rcssplot proposes to customize base-graphics plots using cascading style sheets (css) instead. Cascading style sheets are extensively used in web design because they increase productivity and ease code maintenance. The idea behind the Rcssplot package is to port these advantages to R and to display data in different styles, like in the two figures below, with minimal effort.

In practice, we would start using Rcssplot by writing custom settings into a css file. For example, to set the style of points objects, we would create a file foo.styles.Rcss with definitions such as

points.foo {
  cex: 1.0;
}

points.bar {
  cex: 0.3;
  pch: 19;
}

In the R environment, we would parse these css definitions into an R object,

library("Rcssplot")
foo.styles <- Rcss("foo.styles.Rcss")

Assuming that we have a custom plot function styledPlot, we would then create two visualizations of the same data object like this

styledPlot(data, Rcss=foo.styles, Rcssclass="foo")
styledPlot(data, Rcss=foo.styles, Rcssclass="bar")

With this approach, despite substantial customizations through style sheets, the R code stays tidy. Other benefits include

More examples of styled plots are available on www.rcssplot.org/examples.