1

I was attempting to overlay two plots using ggplot2, I can graph them individually, but I want to overlay them to show a comparison. They have the same y axis. The y axis is a score from 0 to 100, the x axis is a specific date in the month (from a range of 3 weeks)

Here is what I have tried:

data <- read.table(text = Level5avg, header = TRUE)
data2 <- read.table(text = Level6avg, header = TRUE)
colnames(data) = c("x","y")
colnames(data2) = c("x","y")
ggplot(rbind(data.frame(data2, group="a"), data.frame(data, group="b")), aes(x=x,y=y)) + 
          stat_density2d(geom="tile", aes(fill = group, alpha=..density..), contour=FALSE) + scale_fill_manual(values=c("b"="#FF0000", "a"="#00FF00")) + geom_point() + theme_minimal()

When I do this, I get a strange graph that has several dots, but I'm not sure if my code is right, since I can't distinguish the data. I want to add 3 more (small) datasets to the plot, if it is possible. If it is possible, how do I make it into a line graph in order to distinguish the datasets?


Note: I was under the impression ggplot would work for my purposes because of this post (and several other posts on this site advised using ggplot as opposed to Lattice). I'm not sure if what I want is possible, so I came here.

Data sets:

dput(data) structure(list(x = structure(1:6, .Label = c("10/27/2015",     
"10/28/2015", 
"10/29/2015", "10/30/2015", "10/31/2015", "11/1/2015"), class = "factor"), 
y = c(0, 12.5, 0, 0, 11, 43)), .Names = c("x", "y"), class = "data.frame",      
row.names = c(NA, -6L))

dput(data2) structure(list(x = structure(1:3, .Label 
=c("10/28/2015","10/31/2015", 
"11/1/2015"), class = "factor"), y = c(0, 0, 41.5)), .Names = c("x", 
"y"), class = "data.frame", row.names = c(NA, -3L))

I've now managed to get my overlay, but is there a way to organize the horizontal axis? The dates have no order.

Community
  • 1
  • 1
nodel
  • 471
  • 6
  • 22

1 Answers1

0

It seems to me that the answer that you are basing your plots on uses density plots that are not useful for your data. If you are just looking for some line plots with points, you could do the following (note I created a dataframe outside of the ggplot() call to make it look a little cleaner):

data$group <- "b"
data2$group <- "a"
df <- rbind(data2,data)
df$x <- as.Date(df$x,"%m/%d/%Y")
ggplot(df,aes(x=x,y=y,group=group,color=group)) + geom_line() + 
  geom_point() + theme_minimal()

Note that by converting the date, the dates end up in the right order all on their own.

enter image description here

Sam Dickson
  • 5,082
  • 1
  • 27
  • 45
  • Interesting use of rbind, is there any way to order the date chronologically? – nodel Nov 23 '15 at 22:50
  • I added `as.Date()` to convert the dates. Once their in the right format, `ggplot()` puts them in the right order automatically. – Sam Dickson Nov 24 '15 at 13:55