Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

plot

r

ggplot2

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

like image 571
neversaint Avatar asked Jan 31 '13 10:01

neversaint


People also ask

How do you plot a density plot in R?

To create a density plot in R you can plot the object created with the R density function, that will plot a density curve in a new R window. You can also overlay the density curve over an R histogram with the lines function. The result is the empirical density function.

What is a density plot in Ggplot?

Data Visualization using GGPlot2. A density plot is an alternative to Histogram used for visualizing the distribution of a continuous variable. The peaks of a Density Plot help to identify where values are concentrated over the interval of the continuous variable.

How do you use density command in R?

In R Language we use the density() function which helps to compute kernel density estimates. And further with its return value, is used to build the final density plot. Parameters: x: the data from which the estimate is to be computed.


1 Answers

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

like image 175
Arun Avatar answered Oct 11 '22 01:10

Arun