[R] Adding lines in ggplot2

Joshua Wiley jwiley.psych at gmail.com
Wed Jan 5 04:15:14 CET 2011


Hi Eduardo,

To shamelessly borrow from the Princess Bride:

“Why do you use a data frame? Are you touched in the head?
"Oh no. It's just they're terribly practical. I think everyone will be
using them in the future.”

Using data frames is what Hadley intended, and once you get used to
it, it is not nearly as restrictive as you might think.  This does
what you want, I believe.  Rather than creating extraneous variables,
I simply perform various transformations on 'x' within the plotting
code.

require(ggplot2)
dfm <- data.frame(x = 1:10)

qplot(x = x, y = sqrt(x), data = dfm, geom = "line",
  colour = I("darkgreen")) +
  geom_line(aes(x = x, y = log(x)), colour = "red")

Cheers,

Josh


On Tue, Jan 4, 2011 at 6:56 PM, Eduardo de Oliveira Horta
<eduardo.oliveirahorta at gmail.com> wrote:
> Hello,
>
> this is probably a recurrent question, but I couldn't find any answers that
> didn't involve the expression "data frame"... so perhaps I'm looking for
> something new here.
>
> I wanted to find a code equivalent to
>
>> x=sqrt(1:10)
>> y=log(1:10)
>> plot(1:10, x, type="lines", col="darkgreen")
>> lines(1:10, y, col="red")
>
> to use with ggplot2. I've tried
>
>> x=sqrt(1:10)
>> y=log(1:10)
>> qplot(1:10, x, geom="line", colour=I("darkgreen"))
#####
note you would also need a + after the qplot() code to add geom_line()
#####
>> geom_line(1:10, y, colour="red")
> Error: ggplot2 doesn't know how to deal with data of class numeric
>
> but it seems that the "data frame restriction" is really very restrictive
> here. Any solutions that don't imply using as.data.frame to my data?
>
> Thanks in advance, and best regards!
>
> Eduardo Horta
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list