"manipulate" command help

pacificprince's Avatar

pacificprince

06 Aug, 2012 04:37 PM

Hi,
I am exploring the "manipulate" command in RStudio (which I absolutely love, BTW). Specifically, I am trying to vary the y variable in the diamonds dataset as follows:

                  library("ggplot2")
                  library("manipulate")
                  manipulate({p<- ggplot(data, aes(carat, s)) + geom_point() 
                              p}, 
                  s = picker(initial="Depth", "Depth"=data$depth, "Price"=data$price))

I have tried
1. "Depth" = depth, "Price"= price, and
2. "Depth" = "depth", "Price" = "price",
but all end up with the following error:

                 Error in eval(expr, envir, enclos) : object 's' not found

What is the correct way of doing this?

Thanks

  1. Support Staff 2 Posted by Josh Paulson on 06 Aug, 2012 07:39 PM

    Josh Paulson's Avatar

    Hello,

    Perhaps it might be better to pass in a custom function to manipulate rather than the specific commands to ggplot(). This would make sure everything is evaluated and picked up as a "variable" to manipulate around since there are multiple commands being entered. Take a look at the following example:

    example <- function(x.max){
      plot(cars, xlim=c(0,x.max))
      abline(h=mean(cars$dist[1:x.max]), col="blue", lty=2)
    }
    
    manipulate(
      example(x.max),
      x.max=slider(0,25, step=5)
    )
    

    Feel free to post back if you get this working as it'd be great to see.

    Josh

  2. 3 Posted by pacificprince on 09 Aug, 2012 06:14 PM

    pacificprince's Avatar

    Hi,
    Thanks for the quick response. I figured it out from a comment by David Douterlungne for using ggplot2 in a function here: http://stackoverflow.com/questions/5106782/use-of-ggplot-within-ano...

    and I got it to work like so for the diamonds dataset

    library(ggplot2)
    library(manipulate)
    
    pltdata <- function(data, yvar) {data$yvar<-data[,yvar]
                                          p <- ggplot(data, aes(carat, yvar))
                                          p + geom_point(aes(color=yvar, group=yvar))
                                          }
    
    manipulate(pltdata(data, yvar), yvar = picker("Cut"="cut", "Color"="color",    Depth"="depth", "Color"="color"))
    

    With the code, one can now change the y-axis to cycle through various parameters in the data set.

    Hope this helps.

  3. Support Staff 4 Posted by Josh Paulson on 10 Aug, 2012 02:40 PM

    Josh Paulson's Avatar

    Great! Glad you got it working and thanks for posting the solution. Nice to see how it works as well as hopefully it will help others down the road.

    Josh

  4. Josh Paulson closed this discussion on 10 Aug, 2012 02:40 PM.

Comments are currently closed for this discussion. You can start a new one.