How to set fill alpha in geom_box to number of observations in coefficient
I need to draw a set of graphs where data is grouped by factors. I would also like to set a value alpha
for each block to represent the number of observations in each factor. The more observations for a given factor, the higher alpha
.
Using the data mpg
as an example ...
Drawing a plot is simple:
library(ggplot2)
ggplot(mpg, aes(x=factor(class), y=displ)) +
geom_boxplot(aes(fill="red", alpha=10)) +
scale_fill_manual(values=c("red"="red"),guide="none") +
scale_alpha(range=c(0,1), guide="none")
And calculating the number of observations for each is class
simple using plyr
:
ddply(mpg, .(class), nrow)
class V1
1 2seater 5
2 compact 47
3 midsize 41
4 minivan 11
5 pickup 33
6 subcompact 35
7 suv 62
I'm sure ggplot2
there is a clever way to do this inside , but I've run out of ideas.
Thank!
source to share
If you pull alpha
from aesthetic (aes)
, then you can provide a value alpha
based on length
each class
directly like this:
ggplot(mpg, aes(x=factor(class), y=displ)) +
geom_boxplot(aes(fill="red"),
alpha = table(mpg$class) / max(table(mpg$class))) +
scale_fill_manual(values=c("red"="red"), guide = "none")
You get the following:
source to share