R语言 舍入百分比和百分比位置

46scxncf  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(142)

我试着做一个geom_bar图,现在我想要百分比的酒吧。他们在那里,但不是在好的地方...有人知道如何解决这个问题吗?

filter(D=="D") %>%
  group_by(Operatiejaar, Ligging_compleet) %>%
  summarise(cnt = n()) %>%
  mutate(Percentage = formattable::percent(cnt / sum(cnt)))

ggplot(data=Data) +
  aes(x=Operatiejaar, y=cnt, fill=Ligging_compleet, group = Operatiejaar) +
  geom_bar(stat = "identity", width = 0.9, position = "dodge2") +
  ggtitle(
    label = "Ligging",
    subtitle = "Verhoudingen") +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5)) +
  xlab("Jaar") +
  ylab("Aantallen") +
  labs(fill = "Ligging") +
  geom_text(
    aes(label = Percentage, group = Operatiejaar), 
    color = "dark grey", 
    position = position_dodge(width = 1),
    vjust = -0.5,
    hjust = 0,
    size = 3,
    angle = 90)

现在,这个数字是这样的:

我比较喜欢的两件事:

  • 每个条形图上方的百分比
  • 百分比四舍五入到零位小数而不是现在的2位小数
m0rkklqb

m0rkklqb1#

这应该工作。也看看这里:Position geom_text on dodged barplot

library(tidyverse)

set.seed(123)
values <- sample(1:100, 100, replace=T)
name <- rep(LETTERS[1:4], 25)
year <- rep(c("2018", "2019"), 50)

df <- tibble(name, values, year)

df %>%
  group_by(name, year) %>%
  summarise(sum=sum(values)) %>%
  ungroup %>%
  mutate(perc= round(sum/sum(sum), digits = 2)*100) %>%
  ggplot(aes(x=year, y=perc, fill=name))+
  geom_col(position = "dodge")+
  geom_text(aes(label= paste0(perc, "%")), vjust=-0.3, 
            position = position_dodge(width = 0.9))
#> `summarise()` has grouped output by 'name'. You can override using the
#> `.groups` argument.

创建于2023-04-25带有reprex v2.0.2

相关问题