0

My data frame is as follows

   School Gender Value ColorGroup
1 School1   Male    10      1Male
2 School1 Female    30    1Female
3 School2   Male    40      1Male
4 School2 Female    70    1Female
5 School3   Male     5      2Male
6 School3 Female    90    2Female

I can create the following bar chart

cols33 <- c("1Male" = "yellow", "1Female" = "orange", "2Male" = "red", "2Female" = "blue") 

ggplot(data=data2, aes(x=School, y=Value, group = Gender,fill = ColorGroup)) + 
  geom_bar(stat = "identity", position = position_dodge(), width =  0.5) + 
  scale_fill_manual(name="",values=cols33)

enter image description here

I am able to hide all the legends by adding the following to my code.

guides(fill = FALSE)

enter image description here

What I wish to do, is just keep the legends for School3 and remove the ones for School1 and School2.

I also tried the following by using two geom_bar commands in my code and specifying show.legend = FALSE in one of them but it does not work and I get the same chart as before

ggplot(data=data2, aes(x=School, y=Value, group = Gender)) + 
  geom_bar(stat = "identity", position = position_dodge(), aes(fill = ColorGroup),width =  0.5, show.legend = FALSE) + 
  geom_bar(data = subset(data2,School == "School3"),aes(fill = ColorGroup),stat = "identity", position = position_dodge(), width =  0.5) + 
  scale_fill_manual(values=cols33) 

enter image description here

Please can you help me understand how this can be achieved.

Adding out of dput(data2)

structure(list(School = structure(c(1L, 1L, 2L, 2L, 3L, 3L), .Label = c("School1", 
"School2", "School3"), class = "factor"), Gender = structure(c(2L, 
1L, 2L, 1L, 2L, 1L), .Label = c("Female", "Male"), class = "factor"), 
    Value = c(10L, 30L, 40L, 70L, 5L, 90L), ColorGroup = structure(c(2L, 
    1L, 2L, 1L, 4L, 3L), .Label = c("1Female", "1Male", "2Female", 
    "2Male"), class = "factor")), .Names = c("School", "Gender", 
"Value", "ColorGroup"), row.names = c(NA, -6L), class = "data.frame")
Vik G
  • 539
  • 3
  • 8
  • 22
  • Can you run `dput(data2)` and add the output to your question? See more here: [How to make a great R reproducible example?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Tung May 27 '18 at 00:34
  • Hi @Tung - I have added the data to the question, will go through the link and use it in the future. – Vik G May 27 '18 at 00:38
  • 6
    Inside your `scale_fill_manual`, set `breaks = c("2Female", "2Male")`. The other groups will get colored but not appear in the legend. – camille May 27 '18 at 00:51
  • Thanks a ton @camille. That worked really well. – Vik G May 27 '18 at 01:07

0 Answers0