1

I am trying to create some rather rudimentary line graphs but can't seem to find the proper functions. I can use the mtcars dataset to try to describe what I want to do, and I hope you'll be able to give me a start in the right direction.

I want to plot cyl on the x-axis and the MEAN value of disp (for each value of cyl) on the y-axis. Using the whole dataset. Then on TOP of that, I want to plot cyl on the x-axis and the mean value of disp on the y-axis BUT ONLY WHEN VS == 1 . Then the same thing, a similar subgroup, for when vs==0. So there will be three lines, each tracing cyl vs disp. Eventually I'll make these different colors/styles too, but for now I'm just trying to get the line graph.

Any thoughts? Many thanks!

garson
  • 1,505
  • 3
  • 22
  • 56

2 Answers2

1

Using stat_summary within ggplot2:

enter image description here

library(ggplot2)
ggplot() + 
# cyl on the x-axis and the MEAN value of disp (for each value of cyl) 
 stat_summary(aes(x=cyl,y=disp,col='all vs'),data=mtcars,fun.y='mean',geom='line') +
#  cyl on the x-axis and the mean value of disp on the y-axis BUT ONLY WHEN VS == 1 . 
 stat_summary(aes(x=cyl,y=disp,col='vs=1'),data=subset(mtcars,vs==1),
          fun.y='mean',geom='line') +
# Then the same thing, a similar subgroup, for when vs==0. 
 stat_summary(aes(x=cyl,y=disp,col='vs=0'),data=subset(mtcars,vs==0),
          fun.y='mean',geom='line')  +
 theme(legend.title=element_blank())
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • it would be nice if R/ggplot had a convenient data structure for *non-exclusive* groupings (like the `lattice` package's "shingle"); one could then make a grouping (all, group-0, group-1) – Ben Bolker Oct 19 '14 at 17:10
1

You can use stat_summary to do this sort of thing, although for more complex summaries it may actually be easier to do it up-front (e.g. using dplyr or plyr::ddply) and then feed it to ggplot2.

library("ggplot2"); theme_set(theme_bw())
ggplot(mtcars,aes(cyl,disp))+stat_summary(fun.y=mean,
                                          geom="line",
                                          lwd=1.5)+
     stat_summary(aes(lty=factor(vs)),fun.y="mean",geom="line")+
   scale_x_continuous(breaks=c(4,6,8),labels=c("four","6","8"))                

enter image description here

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Yes! Thank you. One more question if you don't mind: I would like to change just one of the x-axis labels so that instead of 4 it says "four" in letters (or some other word of my choosing.) (Let me know if I should submit this as a new question.) – garson Oct 19 '14 at 16:43