Jeff238
Jeff238

Reputation: 428

Grouped boxplot with two groups but one colour and one legend variable

For this sample df

df = data.frame(name = c("Bob","Bob","Bob","Bob","Jerry","Jerry","Jerry","Jerry"),
                score = c(2,3,4,5,6,7,8,9),
                group = c("Pre","Post","Pre","Post","Pre","Post","Pre","Post"))

I want to group the boxplots by the group variable hence the fill argument but I want to only have one colour and one label in the legend, however if I use the scale_fill_manual argument as such:

df %>% ggplot(aes(x=name,y=score,fill = group)) + geom_boxplot() + 
    scale_fill_manual(labels = c("Exam"),values = c("green","green"))

The resulting label will show NA so is there any way to either remove one part of the label or how to make it such that there is only one label for the new colour scheme? (I also tried using the breaks argument as suggested by some posts on stackoverflow but then the whole legend disappears). Thanks!

enter image description here

Upvotes: 0

Views: 211

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

Use the group aesthetic for grouping, not the fill aesthetic. If you want everything filled the same and you want a fill legend, set the fill aesthetic to a constant (a non-numeric constant so it's treated as a categorical variable).

df %>% 
  ggplot(aes(x=name,y=score,group = interaction(name, group), fill = "a")) +
  geom_boxplot() + 
  scale_fill_manual(labels = c("Exam"), values = "green")

enter image description here

Upvotes: 4

Related Questions