Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparency in boxplot legend keys using R and ggplot2

I am trying to make boxplots with a transparent fill and a corresponding legend. The plotting with alpha values works fine except that the legend keys do not have transparent fills. The following example illustrates the difficulty:

dat <- data.frame(x=c('a', 'b', 'c'), y = runif(300), z = c('d', 'e', 'e'))
ggplot(dat) + geom_boxplot(aes(x, y, fill = z, colour = z), alpha = 0.2)

Boxplot with transparencies in fill, but not int the legend

Is there a way to make the fill values in the legend keys transparent too?

SessionInfo()
R version 2.14.0 (2011-10-31)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)
ggplot2_0.8.9

Thanks in advance for any tips on this issue.

An example where the alpha mapping works is the following

ggplot(dat) + geom_point(aes(x, y, fill = z, colour = z, shape = z), alpha = 0.2)

Plot where alpha mapping works fine

like image 227
yellowcap Avatar asked Dec 14 '11 11:12

yellowcap


People also ask

How do you make a boxplot transparent in R?

Be default, the boxplot created in base R or by using ggplot2 are not transparent in nature. If we want to create a transparent boxplot then we can use bwplot function from lattice package.

How can you create a boxplot using ggplot2?

In ggplot2, geom_boxplot() is used to create a boxplot. Let us first create a regular boxplot, for that we first have to import all the required libraries and dataset in use. Then simply put all the attributes to plot by in ggplot() function along with geom_boxplot.

What do Ggplot Boxplots show?

The boxplot compactly displays the distribution of a continuous variable. It visualises five summary statistics (the median, two hinges and two whiskers), and all "outlying" points individually.


1 Answers

The solution I've used in the past is this one... its a huge hack but works.

dat <- data.frame(x=c('a', 'b', 'c'), y = runif(300), z = c('d', 'e', 'e'))
dummy <- dat
dummy$z <- factor(dummy$z)
dummy <- dummy[1,]
dummy[,2]<-NaN
ggplot() + 
geom_boxplot(data=dat,aes(x, y, fill = z, colour = z), alpha = 0.2,legend=FALSE) +
geom_density(data=dummy,aes(x, fill = z, colour = z), alpha = 0.2)

I usually use it when I'm making a geom_text plot, but want the legend to show as points or blocks. But it works for this instance too.

In case Hadley is paying attention to this thread, I've found myself wanting a plot=T/F option that works like the legend option for this situation.

like image 107
Justin Avatar answered Sep 24 '22 01:09

Justin