Fatima Chaudhary
Fatima Chaudhary

Reputation: 5

Why is my legend not showing for my bar graph?

In this image you can see that my bar graph does not have a legend

enter image description here

My code was:


library(ggbeeswarm)
library(ggpubr)
library(ggplot2)

ggplot(data = ciber.1, aes(fill = cell_type, x = wcc_group, y = measurement)) +
  geom_bar(position = "fill", stat = "identity")  + 
  scale_fill_manual(values = c("dodgerblue4", "dodgerblue2", "deepskyblue1", "deeppink4", 
                               "deeppink1", "hotpink3", "lightpink3", "lightpink2", 
                               "lightpink1", "lightpink", "darkorchid4", "darkorchid1", 
                               "mediumpurple3", "thistle3", "thistle2", "thistle", 
                               "navajowhite3", "navajowhite1", "springgreen3", 
                               "springgreen", "chocolate4", "indianred1")) + 
  theme(legend.position = 'none') +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(x = "WCC Group", y = "Leukocytes", title = "Division of leukocytes in WCC Groups") + 
  theme(strip.background = element_rect(fill="lightblue", size=2, color="black")) +
  theme(strip.text = element_text(size = 15, face = "bold")) +
  scale_y_continuous(expand = expansion(mult = c(0.05,0.15) ))

Upvotes: 0

Views: 94

Answers (1)

seagullnutkin
seagullnutkin

Reputation: 321

You need to remove the + theme(legend.position = "none")

This should show the legend:

library(ggbeeswarm)
library(ggpubr)
library(ggplot2)

ggplot(data = ciber.1, aes(fill = cell_type, x = wcc_group, y = measurement)) +
  geom_bar(position = "fill", stat = "identity")  + 
  scale_fill_manual(values = c("dodgerblue4", "dodgerblue2", "deepskyblue1",  
                               "deeppink4", "deeppink1", "hotpink3", 
                               "lightpink3", "lightpink2", "lightpink1", 
                               "lightpink", "darkorchid4", "darkorchid1", 
                               "mediumpurple3", "thistle3", "thistle2", 
                               "thistle", "navajowhite3", "navajowhite1",
                               "springgreen3", "springgreen", "chocolate4",
                               "indianred1")) +
  labs(x = "WCC Group", y = "Leukocytes", title = "Division of leukocytes in WCC Groups") + 
   theme(strip.background = element_rect(fill="lightblue", size=2, color="black"),
         strip.text = element_text(size = 15, face = "bold"),
         axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_y_continuous(expand = expansion(mult = c(0.05,0.15) ))

Also you can include all the theme arguments inside of one theme() function. That might make it easier to keep track of what arguments you've included.

Upvotes: 3

Related Questions