0

I would like to use ggplot.Predict (from the rms package) in a function to produce graphs automatically:

library(rms)

ddist <- datadist(iris); options(datadist="ddist")

mod <- ols(Sepal.Length ~ Petal.Length, data=iris)

p.plot <- function(pred, ttl) {
          ggplot(pred, 
          addlayer=labs(title=ttl))
}

plot.title <- "Sepal length"

p.plot(Predict(mod), plot.title) 

This results in an "Error in labs(title = ttl) : object 'ttl' not found" The following however works without problems.

ggplot(Predict(mod), addlayer=labs(title=plot.title)) 
divibisan
  • 11,659
  • 11
  • 40
  • 58
user169605
  • 141
  • 8
  • 1
    What package does `ggplot.Predict()` come from? That's a very unusual way to overload the `ggplot` function. – MrFlick Jun 21 '18 at 12:41
  • The `rms` package. – user169605 Jun 21 '18 at 13:02
  • When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Right now it's hard to test your code since we don't know exactly what you are passing to this function. – MrFlick Jun 21 '18 at 14:46
  • But rather than using `addlayer=`, try just adding `+labs(title=ttl)` after the `ggplot()` call. – MrFlick Jun 21 '18 at 14:47
  • Thank you very much - this solves the problem. The error seems to result from the way ggplot.Predict passes on variables to addlayer. – user169605 Jun 21 '18 at 15:49

1 Answers1

1

Answered by MrFlick in the comments:

Rather than using addlayer=, try just adding + labs(title=ttl) after the ggplot() call:

p.plot <- function(pred, ttl) {
          ggplot(pred) +
              labs(title=ttl)
}
divibisan
  • 11,659
  • 11
  • 40
  • 58