ddply和ggplot - 没有产生情节

时间:2013-11-18 12:52:08

标签: r ggplot2 plyr

我有一个数据如下:

> dput(qq)
structure(list(SIC = c(50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 
50, 50, 50, 50, 50, 50, 50, 50, 50, 50), AVGAT = c(380.251, 391.3885, 
421.72, 431.83, 483.715, 600.0715, 698.5945, 733.814, 721.426, 
706.0265, 698.41, 697.9565, 720.761, 855.5245, 1023.226, 1214.8215, 
1369.7605, 1439.2765, 1602.3845, 1949.69), ADA = c(0.0223312309851002, 
0.00984600086327487, 0.0199212814576842, 0.0562291585405388, 
0.0155376903911516, 0.0195296616004618, 0.00650206622557842, 
0.0295510054117198, 0.0471091745681615, 0.0898164879903691, 0.154998113255882, 
0.0347106350470676, 0.109407241662021, 0.057428893735577, 0.0637457846236655, 
0.0584883505633773, 0.0439293152619417, 0.030699982198924, 0.00900414418496609, 
0.0293862740698763), NLEAD = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("SIC", "AVGAT", "ADA", 
"NLEAD"), row.names = c(NA, 20L), class = "data.frame")

当我运行以下代码时,代码不会绘制任何内容:

clusmypath <- file.path("C:", "Users", "Swordfish", "Dropbox", "aaa.pdf");
pdf(file = clusmypath);
library(ggplot2);
ww <- ddply(qq, .(SIC), function(p){ggplot(p,aes(x=AVGAT,y= ADA, color = NLEAD)) + geom_point(shape=1) ;return(p)});
dev.off();

然而,当我绘制完整数据时:

clusmypath <- file.path("C:", "Users", "Swordfish", "Dropbox", "aaa.pdf");
pdf(file = clusmypath);
library(ggplot2);
ggplot(qq, aes(x = AVGAT, y = ADA, color = NLEAD)) + geom_point(shape=1)  
dev.off();

我得到了一个情节。如何使ddply部分工作?感谢。

1 个答案:

答案 0 :(得分:2)

脚本中的

return(p)不会返回图表。 p指的是数据框qq的每个子集。一般来说,要返回ggplot内部函数生成的图表,您需要使用print(请参阅FAQ 7.22)。但是,在您要保存图表的特定情况下,您不需要print

多个PDF文件

如果你想在每个级别的'SIC'中找到一个文件,你可以试试这样的东西。当您仅为其副作用调用函数时d_ply非常有用,就像我们从绘图中保存输出时一样。您可以使用pdf代替some-plotting / dev.off / ggsave

d_ply(qq, .(SIC), function(p){
  ggplot(p, aes(x = AVGAT, y = ADA, color = NLEAD)) + geom_point(shape = 1)
  ggsave(file = paste0(unique(p$SIC), ".pdf"))
  })

一个包含多个页面的PDF文件

如果您想要一个PDF文件,每个级别的“SIC”有一个页面,您可以使用base函数pdf.print = TRUE中的d_ply参数。

# create a new SIC variable with two levels, for a more realistic test of the function
qq$SIC2 <- rep(c(50, 100), each = 10)

pdf(file = "aaa.pdf")

d_ply(qq, .(SIC2), .print = TRUE, function(p){
ggplot(p, aes(x = AVGAT, y = ADA, color = NLEAD)) + geom_point(shape = 1)
})

dev.off()