我正在嘗試創建一個堆疊條形圖,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)
這是圖表的輸出:

我如何將百分比放在首位?
uj5u.com熱心網友回復:
position = "stack"也可以在里面使用geom_text:
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)

uj5u.com熱心網友回復:
為避免混淆,我會將其包含在條形圖中,而不是將其放在頂部(因為您的arepercent_final中的其他值)。dfNA
示例代碼:
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()
陰謀:

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/444193.html
