Interactive Plotting with Manipulate in the RStudio IDE


Interactive Plotting with Manipulate

The RStudio IDE works with the manipulate package to add interactive capabilities to standard R plots. This is accomplished by binding plot inputs to custom controls rather than static hard-coded values.

Basic Usage

The manipulate function accepts a plotting expression and a set of controls (e.g. slider, picker, or checkbox) which are used to dynamically change values within the expression. When a value is changed using its corresponding control the expression is automatically re-executed and the plot is redrawn.

For example, to create a plot that enables manipulation of a parameter using a slider control you could use syntax like this:

manipulate(plot(1:x), x = slider(1, 100))

After this code is executed the plot is drawn using an initial value of 1 for x. The plot includes a gear icon, which you can click to open a slider control that changes the value of x from 1 to 100.

Slider Control

The slider control enables manipulation of plot variables along a numeric range. For example:

  plot(cars, xlim=c(0,x.max)),  

Results in this plot and manipulator:

Slider controls also support custom labels and step increments.

Picker Control

The picker control enables manipulation of plot variables based on a set of fixed choices. For example:

          beside = TRUE, main = factor),
  factor = picker("GNP", "Unemployed", "Employed"))

Results in this plot and manipulator:

Picker controls support arbitrary value types, and can also include custom user-readable labels for each choice.

Checkbox Control

The checkbox control enables manipulation of logical plot variables. For example:

  boxplot(Freq ~ Class, data = Titanic, outline = outline),
  outline = checkbox(FALSE, "Show outliers"))

Results in this plot and manipulator:

The manipulate package documentation contains additional details on all of the options available for the various control types.

Combining Controls

Multiple controls can be combined within a single manipulator. For example:

  plot(cars, xlim = c(0, x.max), type = type, ann = label),
  x.max = slider(10, 25, step=5, initial = 25),
  type = picker("Points" = "p", "Line" = "l", "Step" = "s"),
  label = checkbox(TRUE, "Draw Labels"))

Results in this plot and manipulator: