ddply,ggplot和同一页面上的多个图

时间:2013-11-22 22:08:46

标签: r ggplot2 plyr

我正在通过以下代码在多个页面上绘制图表:

pdf(file = "ADAMean_By_Group1.pdf");
  d_ply(dacc, .(SIC), .print = TRUE, function(x){
      ggplot(x, aes(x = PER)) + 
      geom_line(aes(y = MEAN, group = NLEAD, color = NLEAD)) +
  })
  dev.off();

我想减少页数,并在同一页面上有多页图表。比方说,同一页面上有4个图表(2行2列)。我怎样才能做到这一点?

我尝试了各种方法,通过互联网提供,但无法使这些工作。请为此建议解决方案。由于存在ddply,我认为这有点棘手。

数据dacc如下:

> dput(head(dacc[,c("SIC","NLEAD","MEAN","PER")],50))
structure(list(SIC = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 
10, 10, 10, 10, 10, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 
12, 12, 12, 12), NLEAD = c("0", "0", "0", "0", "0", "0", "0", 
"0", "0", "0", "1", "1", "1", "1", "1", "1", "1", "1", "0", "0", 
"0", "0", "0", "0", "0", "0", "0", "0", "1", "1", "1", "1", "1", 
"1", "1", "1", "1", "0", "0", "0", "0", "0", "0", "0", "0", "0", 
"0", "1", "1", "1"), MEAN = c(0.0412326905353457, 0.0451549825189391, 
0.048346878393873, 0.0549350094483683, 0.0730158407197195, 0.069153817795241, 
0.0505335160500995, 0.061317755985916, 0.0684815764449659, 0.0940169129245316, 
0.0582861931922358, 0.144592677844448, 0.0967616801627094, 0.219418938031889, 
0.029572456024009, 0.0426391121531116, 0.0891335203743842, 0.0371790985677946, 
0.27466936080368, 0.316047288322806, 0.399779612196661, 0.241800058717666, 
0.298782209496961, 0.280784586232505, 0.321683292079049, 0.286186440113042, 
0.440826914583147, 0.559706666532758, 0.256427311906362, 0.324337469833082, 
0.61264951851092, 0.249524284265047, 0.503753962899658, 0.314965901129344, 
0.329647650268623, 0.289924074761747, 0.409961187505677, 0.044341055684329, 
0.0298866866711071, 0.0494858483864846, 0.0252166835930562, 0.0474083585004927, 
0.0600282487190496, 0.0393457798051726, 0.0628251930948487, 0.0872080403831907, 
0.0494707607175366, 0.0525395728691009, 0.0407661644145909, 0.0631339860500073
), PER = c(0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.9, 
0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 
0.3, 0.2, 0.1, 0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 
0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.9, 0.8, 0.7
)), .Names = c("SIC", "NLEAD", "MEAN", "PER"), row.names = c(27L, 
173L, 217L, 14L, 227L, 147L, 172L, 79L, 73L, 62L, 241L, 101L, 
112L, 124L, 137L, 165L, 174L, 164L, 1035L, 837L, 675L, 434L, 
924L, 355L, 1103L, 588L, 1117L, 275L, 1126L, 490L, 909L, 673L, 
532L, 908L, 496L, 1003L, 261L, 1269L, 1231L, 1191L, 1206L, 1183L, 
1213L, 1202L, 1211L, 1145L, 1189L, 1259L, 1210L, 1240L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

只是为了完整性,发布我的问题的解决方案。将来可能对某人有用。

plots <- dlply(dacc, .(SIC), function(x){
      ggplot(x, aes(x = PER)) + 
      geom_line(aes(y = MEAN, group = NLEAD, color = NLEADMEAN))
    })

  ml <- do.call(marrangeGrob, c(plots, list(nrow = 2, ncol = 2)));
  ggsave("my_plots.pdf", ml, height = 7, width = 13, units = "in");