Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

ggplot2 - How to add the percentage for one variable in a count ggplot bar graph in R


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can isolate the desired labels in a new dataframe and use another geom_text():

library(ggplot2)
#Data for new labels
Labels <- subset(CRM_df_2,rework_status=='No Rework')
Labels <- Labels[Labels$percent!=0,]
Labels$y <- c(15,37,46,31)
#Plot
ggplot(CRM_df_2, aes(q_year, count, fill = rework_status)) +
  geom_bar(stat = "identity", color = "black", width = 1) +
  geom_text(aes(label= count),
            position=position_stack(0.5), size = 6, color = "black") +
  geom_text(data=Labels,aes(x=q_year,y=y,label=percent))+
  facet_wrap(.~quarter,scales='free_x',nrow = 1,strip.position = 'bottom')+
  theme(strip.text = element_blank(),
        strip.placement = 'outside',
        legend.position = "bottom",
        legend.title = element_blank(),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        plot.title = element_text(hjust = 0.5),
        legend.spacing.x = unit(1.5, 'cm'))+
  labs(title = "CRM First Pass Yield") +
  scale_fill_manual(values = c("No Rework" = "yellowgreen",
                               "Content Rework" = "royalblue",
                               "CO Rework" = "steelblue1"))

Output:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...