Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay violin plots ggplot2

Tags:

plot

r

ggplot2

I would like to plot two series of ten violin plots one over the second :

library(ggplot2)
#generate some data

coco1<-rnorm(10000,0,1)
coco2<-c(runif(10000))
decile<-rbinom(10000,9,1/2)+1
coconut<-data.frame(coco1,coco2,decile)

#draw the violin plots of the coco1 serie
p <- ggplot(coconut, aes(factor(decile), coco1))
p<-p + geom_violin(aes(alpha=0.3,colour="#1268FF"))
p

#draw the violin plots of the coco2 serie
q <- ggplot(coconut, aes(factor(decile), coco2))
q<-q + geom_violin(aes(alpha=0.3,colour="#3268FF"))
q

I would like to plot the violin plot "p" and "q", on the same graph, and I want each violin plot of "q" to be over the corresponding violin plot of "p".

like image 399
Giuliano Avatar asked Oct 20 '13 21:10

Giuliano


People also ask

How to make violin plot in ggplot2?

In ggplot2, as its doc explains, Violin Plot is a blend of geom_boxplot () and geom_density (): a violin plot is a mirrored density plot displayed in the same way as a boxplot. After passing the data to ggplot () function with mapping information, we add geom_violin () function to make simple violin plot.

What is a violin plot in R?

This R tutorial describes how to create a violin plot using R software and ggplot2 package. violin plots are similar to box plots, except that they also show the kernel probability density of the data at different values.

What is the difference between boxplot and violin plot?

A quick look at the violin plot shows that is is very similar to boxplot with additional density information makes the box look like a violin. For example, we have fewer data points at the thin part of violin plot and a lot more data points when the violin plot is thicker/wider.

How do I add dots to a violin plot?

Dots (or points) can be added to a violin plot using the functions geom_dotplot() or geom_jitter() : Change violin plot colors by groups. Change violin plot line colors. Violin plot line colors can be automatically controlled by the levels of dose :


Video Answer


1 Answers

You can just add the geom_violin of the second plot to your first one:

p <- ggplot(coconut, aes(factor(decile), coco1))
p <- p + geom_violin(aes(colour = "#1268FF"), alpha = 0.3)
q <- p + geom_violin(aes(y = coco2, colour = "#3268FF"), alpha = 0.3)

Now, q contains both versions of the violins. enter image description here

By the way: If you want to get rid of the colour legend, you have to specify the colour outside of aes.

like image 79
Sven Hohenstein Avatar answered Sep 20 '22 15:09

Sven Hohenstein