嗨,我只是简单地列出了一个带有名称的数据框。
我想使用lapply在x轴上的绘图中打印数据框的名称。
不幸的是,我的尝试被证明是徒劳的。
lapply函数似乎不喜欢矢量,因此非常希望将我当前的产品通过lapply转换为可读的产品。
set.seed(1:1000)
df <- as.data.frame(replicate(1, rnorm(20)))
df2 <- as.data.frame(replicate(1, rnorm(20)))
df.list <- append(df,df2)
require(reshape2)
require(ggplot2)
melt.df.list <- lapply(df.list, function(x) melt(x))
names(melt.df.list) <- c("Plot1","Plot2")
lapply(melt.df.list, function(x) ggplot(x, aes(x=value)) +
geom_histogram(aes(y=..density..), colour="black", fill="white")+
geom_density(alpha=.2, fill="#FF6666") +
labs(x =
lapply(as.character(names(melt.df.list)), function(y)
paste("Counts","(",y,")", collapse ="+")),
y = "Density") +
xlim(-5, 20))
答案 0 :(得分:3)
到目前为止讨论的三个主要选项的摘要:
# Loop over the names instead
lapply(names(melt.df.list), function(nm) ggplot(melt.df.list[[nm]], aes(x=value)) +
geom_histogram(aes(y=..density..), colour="black", fill="white")+
geom_density(alpha=.2, fill="#FF6666") +
labs(x = paste("Counts","(",nm,")"),
y = "Density") +
xlim(-5, 20))
# Use imap
library(purrr)
imap(.x = melt.df.list,.f = ~ggplot(.x, aes(x=value)) +
geom_histogram(aes(y=..density..), colour="black", fill="white")+
geom_density(alpha=.2, fill="#FF6666") +
labs(x = paste("Counts","(",.y,")"),
y = "Density") + xlim(-5, 20))
# Just write a darn for loop ;)
for (i in seq_along(melt.df.list)){
ggplot(melt.df.list[[i]], aes(x=value)) +
geom_histogram(aes(y=..density..), colour="black", fill="white")+
geom_density(alpha=.2, fill="#FF6666") +
labs(x = paste("Counts","(",names(melt.df.list)[i],")"),
y = "Density") +
xlim(-5, 20)
}