将百分比添加到带有位置=填充的条形图中

问题描述 投票:0回答:1

我创建了堆叠的条形图,条形图内有相应的标签。但是,我想更改绘图,例如position = fill。这使我的情节有些奇怪。任何想法如何解决这个问题?

cat <- c (0,0,0,0,0,1,1,1,1,1)
value <- c(100,200,300,100,300,200,200,200,300,300)
N <- c(15,43,7,53,25,33,5,3,2,2)
year <- c(2014,2017,2018,2016,2015,2014,2016,2018,2017,2015)
exdata <- cbind(cat, value, N, year)

exdata <- as.data.frame(exdata)

exdata2 <- group_by(exdata, year) %>% mutate (pct = paste0((round(value/sum(value)*100, 2))," %"))
exdata2 <- as.data.frame(exdata2)

plot.exdata2 <- ggplot(exdata2, aes(year, value, fill = factor(cat))) +
  geom_bar(stat = "identity", position = "stack") + # position = stack
  geom_text(aes(label = exdata2$pct), position = position_stack(vjust = 0.5), size = 3.2) +
  theme_pubclean()

enter image description here

enter image description here

所需格式:enter image description here

r ggplot2 bar-chart direct-labels
1个回答
0
投票

您可以改用geom_col,因为建议在stat = "identity"时使用。另外,您还必须在"fill"中指定geom_text位置:

ggplot(exdata2, aes(year, value, fill = factor(cat))) +
  geom_col(position = "fill") + 
  geom_text(aes(label = pct), position = position_fill(vjust = 0.5))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.