Ken Williams
Ken Williams

Reputation: 23995

ggplot2: Use %+% to plot new data

I'm hitting a snag when I try to use the %+% operator to redo an existing plot with new data. My code looks like this:

df <- data.frame(ending=now()+hours(0:5), actual=runif(6), pred=runif(6))
p <- ggplot(df, aes(x=ending)) +
  geom_line(aes(y=actual, color='Actual')) +
  geom_line(aes(y=pred, color='Predicted')) +
  ylab('Faults') +
  scale_color_manual('Values', c("Predicted"="red", "Actual"="black"))
p

That works fine. But when I try to substitute a new df, I hit errors:

p1 %+% df
Error in bl1$get_call : $ operator is invalid for atomic vectors

Any thoughts?

Upvotes: 6

Views: 2853

Answers (2)

IRTFM
IRTFM

Reputation: 263411

You can reassign infix operators to infix operators, but I don't think you can then turn them back into regular functions without special effort. Try this instead:

 `%new+%` <- ggplot2::`%+%`

.... and use it as p %+% df, rather than as %+%(a,b)

Upvotes: 2

Ken Williams
Ken Williams

Reputation: 23995

Of course, immediately after I post, I find the answer - it's not ggplot2's %+% operator. Another namespace collision. The mboost package also provides a %+% operator.

I "solved" this by doing detach(package:mboost). I could also solve it by doing something like

replot <- get('%+%', 'package:ggplot2')
replot(p, df)

A solution to avoiding the namespace collision would be best, but I don't know how to do that.

Upvotes: 5

Related Questions