为什么我的条形图没有显示图例?

时间:2021-02-01 01:55:24

标签: r ggplot2

在这张图片中你可以看到我的条形图没有图例

enter image description here

我的代码是:


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) ))

1 个答案:

答案 0 :(得分:3)

您需要删除 + theme(legend.position = "none")

这应该显示图例:

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) ))

您还可以在一个 theme() 函数中包含所有主题参数。这样可以更轻松地跟踪您包含的参数。