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
  • 4,158
  • 7
  • 35
  • 73

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
  • 173,430
  • 21
  • 312
  • 389