我有动态创建的以下数据:
> df <- data.frame( cbind(rnorm(200),rnorm(200, mean=.8),rnorm(200, mean=.9),rnorm(200, mean=1),rnorm(200, mean=.2),rnorm(200, mean=.3)),rnorm(200, mean=4),rnorm(200, mean=.5))
> colnames(df) <- c("w.cancer","w.normal","x.cancer","x.normal","y.cancer","y.normal","z.cancer","z.normal")
> df_log<-log2(df) # ignore the warning with NA
> head(df_log)
我想要做的是在一个面板中创建多个图,如下面的草图使用'facet'。 我怎么能去做呢?
答案 0 :(得分:19)
您必须先准备好数据。我已经在data.frame df
上说明了这一点,因为它是正常的正态分布。
require(ggplot2)
require(reshape2)
df$id <- 1:nrow(df)
df.m <- melt(df, "id")
df.m$grp1 <- factor(gsub("\\..*$", "", df.m$variable))
df.m$grp2 <- factor(gsub(".*\\.", "", df.m$variable))
p <- ggplot(data = df.m, aes(x=value)) + geom_density(aes(fill=grp2), alpha = 0.4)
p <- p + facet_wrap( ~ grp1)
p + scale_fill_brewer(palette = "Set1")
通过将df
替换为df_log
来执行相同操作,您可以获得以下内容:
require(ggplot2)
require(reshape2)
df_log$id <- 1:nrow(df_log)
df.m <- melt(df_log, "id")
df.m$grp1 <- factor(gsub("\\..*$", "", df.m$variable))
df.m$grp2 <- factor(gsub(".*\\.", "", df.m$variable))
p <- ggplot(data = df.m, aes(x=value)) + geom_density(aes(fill=grp2), alpha = 0.5)
p <- p + facet_wrap( ~ grp1)
p