作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在考虑在循环中生成多面直方图。当我在循环中调用facet_wrap 时,就会出现问题。我尝试了不同的选项,但都失败了,并显示以下消息:
Error in layout_base(data, vars, drop = drop) : At least one layer must contain all variables used for facetting
下面是一个可重现的示例。
library(ggplot2)
library(scales) #date_format
## Reproducible example
datatest <- data.frame(
column1 = sample(c("yes", "no"), 50, replace = TRUE),
column2 = sample(c("yes", "no"), 50, replace = TRUE),
column3 = sample(c("yes", "no"), 50, replace = TRUE),
column4 = sample(c("yes", "no"), 50, replace = TRUE)
)
#This function will generate a uniform sample of dates from
#within a designated start and end date:
rand.date=function(start.day,end.day,data){
size=dim(data)[1]
days=seq.Date(as.Date(start.day),as.Date(end.day),by="day")
pick.day=runif(size,1,length(days))
date=days[pick.day]
}
#This will create a new column within your data frame called date:
datatest$date=rand.date("2016-01-01","2016-09-21",datatest)
## Simple frequency plot that works well
histotest <- ggplot(datatest, aes(x = date)) +
geom_histogram(binwidth = 7, fill="#2a87c8", colour="white") +
scale_x_date(limits = c(Sys.Date() - 250, NA), labels = date_format("%b %Y")) +
labs(x = "Period", y = "Count") +
facet_wrap(~ column1 , ncol=1) +
theme(plot.title=element_text(face="bold", size=9),
panel.grid.major = element_line(colour = "white"),
panel.grid.minor = element_blank())
ggsave("out/column1_histo.png", plot=histotest, width=12, height=6,units="in", dpi=300)
问题来了:
## Same plot generated through a loop
## The pb is with the facet_wrap
for (i in 1:4 ) {
rm(variablename)
variablename <- names(datatest)[i]
## histogramme to display event occurence over time
histoloop <- ggplot(datatest, aes(x = date)) +
geom_histogram(binwidth = 7, fill="#2a87c8", colour="white") +
scale_x_date(limits = c(Sys.Date() - 250, NA), labels = date_format("%b %Y")) +
labs(x = "Period", y = "Count") +
## I tried different options but none of them is working
## If I comment the facet_wrap everything's fine...
facet_wrap(~ variablename , ncol=1) +
#facet_wrap(~ names(datatest)[i] , ncol=1) +
#facet_wrap(~ aes_string(names(datatest)[i]) , ncol=1) +
theme(plot.title=element_text(face="bold", size=9),
panel.grid.major = element_line(colour = "white"),
panel.grid.minor = element_blank())
ggsave(filename=paste("out/",variablename,"_histo.png",sep=""), plot=histoloop, width=12, height=6,units="in", dpi=300)
}
最佳答案
按如下方式更改代码(因为变量名是字符串):
facet_wrap(as.formula(paste("~", variablename)) , ncol=1)
关于r - 循环中直方图的facet_wrap : "At least one layer must contain all variables",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39614425/
我是一名优秀的程序员,十分优秀!