create boxplots with transparent colour ggplot2

Seb picture Seb · Dec 5, 2011 · Viewed 29.4k times · Source

I create a graphic with several groups and plotting a geom_boxplot() over a seet of lines. However, it would be nice to colour the boxes transparently so that the lines can be seen.

Here's some sample data:

x11()

name <- c("a", "a", "a", "a", "a", "a","a", "a", "a", "b", "b", "b","b", "b", "b","b", "b", "b")
class <- c("c1", "c1", "c1", "c2", "c2", "c2", "c3", "c3", "c3","c1", "c1", "c1", "c2", "c2", "c2", "c3", "c3", "c3")
year <- c("2010", "2009", "2008", "2010", "2009", "2008", "2010", "2009", "2008", "2010", "2009", "2008", "2010", "2009", "2008", "2010", "2009", "2008")
value <- c(100, 33, 80, 90, 80, 100, 100, 90, 80, 90, 80, 100, 100, 90, 80, 99, 80, 100)

df <- data.frame(name, class, year, value)
df

I draw the graphic with:

p1 <- ggplot(df, aes(year, value))
p1 <- p1 + geom_line(aes(group=name, size=name),colour="#ff2300",alpha=0.5) +     facet_wrap(~ class, scales = "free_y") 
p1 <- p1 + geom_boxplot(aes(group=name))
print(p1)

And on my system the line width in the legend is not correctly displayed. Am I doing something wrong? Thanks in advance!

Answer

Roman Luštrik picture Roman Luštrik · Dec 5, 2011

You can add alpha argument to your boxplot. For example:

geom_boxplot(aes(group=name), alpha = 0.8)

will give you

enter image description here