ddply and ggplot - generating no plot [duplicate]

假如想象 提交于 2019-12-25 06:43:51

问题


I have a data which is given below:

> 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")

When I run the following code, the code doesn't plot anything:

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();

However, when I plot the full data :

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();

I get a plot. How can I make ddply part to work? Thanks.


回答1:


return(p) in your script doesn't return a plot. p refers to each subset of the data frame qq. In general, to 'return' plots produced by ggplot inside functions you need to use print (see FAQ 7.22). However, in your particular case, where you want to save plots, you don't need print.

Several PDF files

If you want one file per level of 'SIC', you may try something like this. d_ply is useful when you call a function only for its side effects, like here when we save the output from a plot. Instead of pdf/some-plotting/dev.off, you may use 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"))
  })

One PDF file with several pages

If you want one PDF file, with one page per level of 'SIC', you may use base function pdf, and the .print = TRUE argument in 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()  


来源:https://stackoverflow.com/questions/20048287/ddply-and-ggplot-generating-no-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!