I am asking you because I have a problem with a legend in ggplot2. Here's a simplified case
library(ggplot2)
library(datasets)
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group, color=group)) + geom_boxplot()
bp +scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"),
name="Experimental\nCondition",
breaks=c("ctrl", "trt1", "trt2"),
labels=c("legend 1", "legend 2", "legend 3")) +
scale_color_manual(values=c("black", "red", "green"),
name="Experimental\nCondition",
breaks=c("ctrl", "trt1", "trt2"),
labels=c("legend 1", "legend 2", "legend 3"))
In this case my legend labels are : "legend 1", "legend 2" and "legend 3"
Now, I would like to have the same labels for my legend : "legend 1" (with still three legend boxes). So my code is :
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group, color=group)) + geom_boxplot()
bp +scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"),
name="Experimental\nCondition",
breaks=c("ctrl", "trt1", "trt2"),
labels=c("legend 1", "legend 1", "legend 1")) +
scale_color_manual(values=c("black", "red", "green"),
name="Experimental\nCondition",
breaks=c("ctrl", "trt1", "trt2"),
labels=c("legend 1", "legend 1", "legend 1"))
But, clearly this is not what I want because from now on, I have 9 legend boxes. Therefore my question is : how in such a case, can I have a legend with three boxes (each one for each boxplot) but with labels for the legend which could be the same ? Besides, why ggplot2 treats my code like this ?
You would help me a lot, if you could help me ! Thanks for your help. Excuse me for my english mistakes, actually I am a non-native.
The problem arises, I think, from how ggplot combines legends together. If they have the same title and labels, they can be combined. I'm guessing that there is a merge involved which, when given duplicate labels, effectively creates an outer join (all possible mixes of the combinations). I'm not sure if there is a right way to fix this, but here is a hack that works:
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group, color=group)) + geom_boxplot()
bp +scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"),
name="Experimental\nCondition",
breaks=c("ctrl", "trt1", "trt2"),
labels=c("legend 1", "legend 1 ", "legend 1 ")) +
scale_color_manual(values=c("black", "red", "green"),
name="Experimental\nCondition",
breaks=c("ctrl", "trt1", "trt2"),
labels=c("legend 1", "legend 1 ", "legend 1 "))
So you have labels which are not the same, but which look the same.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.