plotting two vectors of data on a GGPLOT2 scatter plot using R

Update: several years on now, I almost always use Jonathan's method (via the tidyr package) with ggplot2. My answer below works in a pinch, but gets tedious fast when you have 3+ variables.


I'm sure Hadley will have a better answer, but - the syntax is different because the ggplot(dd,aes()) syntax is (I think) primarily intended for plotting just one variable. For two, I would use:

ggplot() + 
geom_point(data=dd, aes(x_value, Actual_value, group=State_CD), colour="green") + 
geom_point(data=dd, aes(x_value, Predicted_value, group=State_CD), shape = 2) + 
facet_wrap(~ State_CD) + 
theme(aspect.ratio = 1)

Pulling the first set of points out of the ggplot() gives it the same syntax as the second. I find this easier to deal with because the syntax is the same and it emphasizes the "Grammar of Graphics" that is at the core of ggplot2.


you might just want to change the form of your data a little bit, so that you have one y-axis variable, with an additional factor variable indicating whether it is a predicted or actual variable.

Is this something like what you are trying to do?

dd<-data.frame(type=rep(c("Predicted_value","Actual_value"),20),y_value=rnorm(40),
                x_value=rnorm(40),State_CD=rnorm(40)>0)
qplot(x_value,y_value,data=dd,colour=type,facets=.~State_CD)

Just following up on what Ian suggested: for ggplot2 you really want all the y-axis stuff in one column with another column as a factor indicating how you want to decorate it. It is easy to do this with melt. To wit:

qplot(x_value, value, 
      data = melt(dd, measure.vars=c("Predicted_value", "Actual_value")), 
      colour=variable) + facet_wrap(~State_CD)

Here's what it looks like for me: alt text
(source: princeton.edu)

To get an idea of what melt is actually doing, here's the head:

> head(melt(dd, measure.vars=c("Predicted_value", "Actual_value")))
     x_value State_CD        variable      value
1  1.2898779        A Predicted_value  1.0913712
2  0.1077710        A Predicted_value -2.2337188
3 -0.9430190        A Predicted_value  1.1409515
4  0.3698614        A Predicted_value -1.8260033
5 -0.3949606        A Predicted_value -0.3102753
6 -0.1275037        A Predicted_value -1.2945864

You see, it "melts" Predicted_value and Actual_value into one column called value and adds another column called variable letting you know what column it originally came from.


well after posting the question I ran across this R Help thread that may have helped me. It looks like I can do this:

 pg + geom_line(data=dd,aes(x_value, Actual_value,group=State_CD), colour="green") 

is that a good way of doing things? It odd to me because adding the second item has a totally different syntax than the first.