如何解决绘图标签不会出现在分组绘图中的一个条形上方的问题?

时间:2019-05-14 14:57:32

标签: r ggplot2

我在ggplot中制作了一个分组的条形图,我想用number_of_systems标记每个条形。标签会显示出来,但是它们都显示在组中的中间栏,reporting_systems B上。如何编辑geom_text以使标签显示在其适当的条形上方?

data1 <- data.frame(office = c("HR","HR","HR","Comms","Comms","Comms","Legal","Legal","Legal","Accounting","Accounting","Accounting","Admin","Admin","Admin","Policy","Policy","Policy","Research","Research","Research"), reporting_systems = c("A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C"), number_of_systems = c(27,0,0,12,1,4,15,2,15,29,0,0,2,0,0,59,28,46,0,0,0))

reporting_order <- factor(data$reporting_systems, level = c("A","B","C"))

ggplot(data = data1, aes(x = office, y = number_of_systems, fill = reporting_order)) + 
  geom_bar(stat = "identity", position = position_dodge()) +
  xlab("") +
  ylab("Number of Projects") +
  ggtitle("") +
  geom_text(aes(label = number_of_systems, fill = reporting_order), vjust = -0.3, color = "black", size = 4) +
  theme(axis.line = element_line(color = "black"), 
        axis.text = element_text(color = "black", size = 15),
        axis.text.x = element_text(angle = 35, hjust = 1),
        axis.text.y = element_text(angle = 0, hjust = 1), axis.title.y = (element_text(size = 15)),
        panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 0.5),
        panel.background = element_rect(fill = NA), text = element_text(size = 15))

1 个答案:

答案 0 :(得分:1)

有一个非常相似的问题here

答案是在您的geom_text中添加一个位置参数:

ggplot(data = data1, aes(x = office, y = number_of_systems, fill = reporting_order)) + 
  geom_bar(stat = "identity", position = position_dodge()) +
  xlab("") +
  ylab("Number of Projects") +
  ggtitle("") +
  geom_text(position = position_dodge(width=0.9), aes(label = number_of_systems, fill = reporting_order), vjust = -0.3, color = "black", size = 4) +
  theme(axis.line = element_line(color = "black"), 
        axis.text = element_text(color = "black", size = 15),
        axis.text.x = element_text(angle = 35, hjust = 1),
        axis.text.y = element_text(angle = 0, hjust = 1), axis.title.y = (element_text(size = 15)),
        panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 0.5),
        panel.background = element_rect(fill = NA), text = element_text(size = 15))