如何使用'facet'在GGPLOT中创建多个密度图

时间:2013-01-31 10:17:31

标签: r plot ggplot2

我有动态创建的以下数据:

 > 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'。 我怎么能去做呢?

enter image description here

1 个答案:

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

ggplot2_facet_example

通过将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

ggplog2_facet_log