堆积条形图 R 顶部的百分比

Percents on top of stacked bar graph R

我正在尝试在 ggplot2 中创建一个堆叠条形图,并在其顶部显示百分比份额。在看了很多其他帖子后,我找不到解决方案,所以这里有一些示例数据:

# load some libraries
library(ggplot2)

# make basic data frame
df <- data.frame(type = c("A", "A", "B", "B"),
                 year = c(2001,2002, 2001, 2002),
                 count_A = c(3, 2, NA, NA),
                 count_B = c(NA, NA, 8, 1),
                 sum_year_AB =  c(11,3,11,3),
                 total_count_with_irrelevant_types = c(13,14,19,23))

# create single percentage variable for top of bar
df$percent_AB_year = (df$sum_year_AB/df$total_count_with_irrelevant_types)*100
df$percent_AB_year = round(df$percent_AB, 1)
df$percent_final = paste0(df$percent_AB_year, "%")
df$percent_AB_year = ifelse(df$type=="B", NA, df$percent_AB_year)
df$percent_final = ifelse(df$type=="B", NA, df$percent_final)

这是我的条形图代码:

ggplot(df, aes(fill=type, x=year, y=sum_year_AB)) + 
  geom_bar(position="stack", stat="identity", width = .9) +
  labs(fill="Type",
       x = "Year",
       y = "Count",
       title = "Count by Year") +
  scale_x_continuous(breaks = seq(1999,2003,1)) + 
  geom_text(aes(label = percent_final), size = 3) +
  scale_fill_grey(start = .4, end = .6)

这是图形的输出:

如何将百分比置于顶部?

geom_text 中使用 position = "stack" 到:

ggplot(df, aes(fill=type, x=year, y=sum_year_AB)) + 
  geom_bar(position="stack", stat="identity", width = .9) +
  labs(fill="Type",
       x = "Year",
       y = "Count",
       title = "Count by Year") +
  scale_x_continuous(breaks = seq(1999,2003,1)) + 
  geom_text(aes(label = percent_final), size = 3, position = "stack", vjust = -0.2) +
  scale_fill_grey(start = .4, end = .6)

为了避免混淆,我会将其包含在条形图中而不是将其放在顶部(因为 df 中的其他 percent_final 值是 NA)。

示例代码:

library(ggplot2)
library(ggthemes)

ggplot(df, aes(fill=type, x=year, y=sum_year_AB)) + 
  geom_bar(position="stack", stat="identity", width = .9) +
  labs(fill="Type",
       x = "Year",
       y = "Count",
       title = "Count by Year") +
  scale_x_continuous(breaks = seq(1999,2003,1)) + 
  geom_text(aes(label = percent_final),position=position_stack(vjust=0.5), colour="blue", size = 9) +
  theme_economist()

剧情: