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?
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.
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.
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.
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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With