我在这里看到了一些类似的问题,但是没有什么适合我想要的,因为这些问题并没有描述如何从一个组填充中添加一个百分比。我看到了如何将计数和百分比添加到相同的栏中,但我希望每个填充类别的计数和百分比仅为其中一个填充。我有一个ggplot2条形图(见下文),它显示了每个填充类别的计数。我想包括在每个栏顶部的百分比,即“不返工”,但不包括属于其他类别的百分比。因此,在Q4 2020的柱状图顶部,它将显示出75.86%。我已经包含了生成绘图和数据的代码。任何帮助都将不胜感激!
数据:
structure(list(q_year = c("Q1 2020", "Q1 2020", "Q1 2020", "Q2 2020",
"Q2 2020", "Q2 2020", "Q3 2020", "Q3 2020", "Q3 2020", "Q4 2020",
"Q4 2020", "Q4 2020", "Q1 2019", "Q2 2019", "Q3 2019", "Q4 2019"
), prod_bus_grp = c("CRM", "CRM", "CRM", "CRM", "CRM", "CRM",
"CRM", "CRM", "CRM", "CRM", "CRM", "CRM", "CRM", "CRM", "CRM",
"CRM"), rework_status = c("CO Rework", "Content Rework", "No Rework",
"CO Rework", "Content Rework", "No Rework", "CO Rework", "Content Rework",
"No Rework", "CO Rework", "Content Rework", "No Rework", "No Rework",
"No Rework", "No Rework", "No Rework"), count = c(6, 2, 4, 9,
3, 23, 12, 1, 29, 6, 1, 22, 0, 0, 0, 0), quarter = c(1, 1, 1,
2, 2, 2, 3, 3, 3, 4, 4, 4, 1, 2, 3, 4), percent = c(50, 16.7,
33.3, 25.71, 8.57, 65.71, 28.57, 2.38, 69.05, 20.69, 3.45, 75.86,
0, 0, 0, 0)), row.names = c(NA, -16L), class = c("tbl_df", "tbl",
"data.frame"))代码
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") +
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"))

发布于 2021-01-21 15:46:08
您可以在新数据中隔离所需的标签并使用另一个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"))输出:

https://stackoverflow.com/questions/65830729
复制相似问题