Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Use %+% to plot new data

Tags:

r

ggplot2

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?

like image 339
Ken Williams Avatar asked Mar 09 '12 23:03

Ken Williams


2 Answers

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.

like image 62
Ken Williams Avatar answered Sep 22 '22 16:09

Ken Williams


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)

like image 45
IRTFM Avatar answered Sep 22 '22 16:09

IRTFM