1

I have 6 dataframes like the one below, only differing in "count" values. The dataframes are named a1,a2,a3,a4,a5,a6. a1 is given below.

year count
1981 2
1982 8
1983 5
1984 6
1985 6
1986 4
1987 2
1988 2
1989 6
1990 5

I want to make a 6 panel figure like the one below where I have

1. Panel names as a1,a2,a3,a4,a5,a6.
2. x-axis is year for each dataframe
3. y-axis is count for each dataframe

I know how to do this if I had a single dataframe (Melt+Faced_Grid). But how can I do the same in ggplott2 when the data is in 6 different dataframes.

enter image description here

maximusdooku
  • 5,242
  • 10
  • 54
  • 94

1 Answers1

2
set.seed(1001)
a1 <- data.frame(year=2000:2009,count=sample(1:20,size=10,replace=TRUE))
a2 <- data.frame(year=2000:2009,count=sample(1:20,size=10,replace=TRUE))
dList <- setNames(list(a1,a2),paste0("a",1:2))

You can use lapply() to add a frame column to each data set, but plyr::ldply offers a shortcut:

library("plyr")
dAll <- ldply(dList,identity,.id="frame")

Alternatively you can use dplyr::bind_rows, as @Axeman points out in comments above:

library("dplyr")
dAll <- bind_rows(a1,a2,.id="frame")

Now it's easy with facet_wrap():

library("ggplot2")
ggplot(dAll,aes(year,count))+geom_point()+facet_wrap(~frame)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Thank you. I wish I knew R this well.. Can you please tell me what this is doing: "paste0("a",1:2)"? Specially the a? – maximusdooku Oct 12 '15 at 17:12
  • 1
    @maximusdooku If you run that line of code, `paste0("a", 1:2)`, I bet you can figure out what it's doing. If you're stuck, look at the help `?paste0`. – Gregor Thomas Oct 12 '15 at 17:14
  • I got it now. Thank you. – maximusdooku Oct 12 '15 at 17:16
  • Quick question: If I don't want to use serials like a1, a2 etc., and instead want to use some other random names (say, cow,bull,hen,sky,water,space), how would I need to modify this part: paste0("a",1:2)? – maximusdooku Oct 12 '15 at 17:23
  • 2
    `dNames <- c("cow","bull","hen","water","space"); setNames(list(...),dNames)` (or `dList <- list(...); names(dList) <- dNames`) – Ben Bolker Oct 12 '15 at 17:24