【发布时间】:2018-01-30 17:42:01
【问题描述】:
我有大约 300 个站点,分布在多种山区。我正在尝试制作一些有意义的情节。因此,我想按山区类型(类型)对我的数据进行子集化,并通过 ggplot2 绘制它。我想通过for循环或lapply来自动化这个过程,但我都是初学者。
我发现了一些使用 for 循环的好例子:http://www.reed.edu/data-at-reed/resources/R/loops_with_ggplot2.html 或使用 lapply:Use for loop in ggplot2 to generate a list
但是,这两种方法都会生成空白图。我究竟做错了什么?如何修复我的代码?
# Create dummy data
df<- data.frame(loc = rep(c("l1", "l2"), each = 3),
name = rep(c("A", "B"), 3),
grid = c(5,6,7,2,3,5),
area = c(5,10,1,1,3,1),
areaOrig = rep(c(20, 10, 5), each = 2))
df2<-rbind(df, df)
# Create two mountain types types
df2$type = rep(c("y", "z"), each = 6)
创建function 以生成绘图:
require(ggplot2)
type.graph <- function(df2, na.rm = TRUE, ...) {
# Create list of locations
type_list <-unique(df2$type)
# Create a for loop to produce ggpot plots
for (i in seq_along(type_list)) {
# create a plot for each loc in df
plot<-
windows()
ggplot(subset(df2, df2$type == type_list[i]),
aes(x = grid,
y = area)) +
geom_bar(stat = "identity") +
ggtitle(type_list[i]) +
facet_grid(loc ~name)
print(plot)
}
}
type.graph(df2)
使用lapply 生成绘图:
#significant SNPs
type_list <- unique(df2$type)
#create list of ggplots per type
p_re <-
lapply(type_list, function(i){
ggplot(subset(df2, type == type_list[i]),
aes(x = grid,
y = area)) +
geom_bar(stat = "identity")
})
#assign names
names(p_re) <- type_list
#plot
p_re$y
【问题讨论】:
-
您的一个问题来自
plot <- windows()命令(它跨越代码中的多行,但这就是它执行的内容)。因此,您的代码会打开一个新窗口,将结果 (NULL) 存储为plot,创建一个 ggplot 对象但不保存它,然后打印plot(同样是NULL)。如果你把它改成plot <- ggplot(...,就可以了。