Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

r - How to use 'facet' to create multiple density plot in GGPLOT

I have the following data created on the fly:

 > 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)

What I want to do is to create multiple plots in one panel like the sketch below using 'facet'. How can I go about it?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll have to prepare your data first. I've illustrated this on your data.frame df as it is a proper normal distribution.

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

Doing the same by replacing df with df_log you'd get something like this:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...