Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: tailoring legend in ggplot boxplot leaves two separate legends

I have created a faceted boxplot using the ggplot2 package. The R code is as follows:

version.labs <- c(`1`="Version 1.0", `2`="Version 2.0", `3`="Version 3.0", `4`="Version 4.0", `5`="Version 5.0")
ggplot(df, aes(x=factor(Subsystem), y=Risk.value, fill=factor(Version)) ) + 
  geom_jitter(position=position_jitter(width=0.3, height=0.2), aes(colour=factor(Version)), alpha=0.9) +
  geom_boxplot(alpha = 0.5, show.legend = FALSE) + facet_grid(.~Version, labeller = as_labeller(version.labs)) +
  theme(strip.text.x = element_text(size=9, color="black", face="bold"))

The resulting plot looks pretty good (as shown below) exept for the legend.

enter image description here

In the legend I want to change the title as well as the text label for each item. The title should be "Version" and the labels "Version 1.0", ..., "Version 5.0".

I've tried various ways but they all add a new separate legend. The new legend looks good, but the old one is still there which doesn't look good and I can't find a way to remove it.

The last thing I tried was to add the scale_color_manual() function, like this:

scale_color_manual(name = "Version", labels=c("v1.0","v2.0","v3.0","v4.0","v5.0"), values=c("grey","blue","green","red","black"))

This results in a boxplot that looks like this.

enter image description here

As can be seen there are two legends. So, close but no cigar. Any hints on how to solve this are appreciated.

like image 238
Martin Avatar asked Jan 20 '26 18:01

Martin


1 Answers

I figured out the problem. It was that I had placed my aestetic fill function aes() in the general ggplot(). This should instead be placed in geom_boxplot(), otherwise both the general ggplot() as well as the geom_boxplot() will add a legend. So I fixed that, and then I used guides() to update the title in the geom_boxplot() legend. The full code looks as follows:

ggplot(df, aes(x=factor(Subsystem), y=Risk.value) ) + 
  geom_jitter(position=position_jitter(width=0.3, height=0.2), aes(colour=factor(Version)), alpha=0.9) +
  geom_boxplot(alpha = 0.5, show.legend = FALSE, aes(fill=factor(Version))) + facet_grid(.~Version, labeller = as_labeller(version.labs)) +
  theme(strip.text.x = element_text(size=9, color="black", face="bold")) +
  labs(x="Risk distribution per software version and subsystem type", y="Normalized risk value") + 
  guides(color=guide_legend("Version"))

The final plot looks like this, which I'm happy with.

Final plot

like image 180
Martin Avatar answered Jan 22 '26 09:01

Martin