如何在ggplot2中按组显示摘要统计信息

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

我有一个带有三个变量的数据帧:手册,品牌和卷。

这是我的情节。如何在图表中的某处显示制造商的总体积和体积百分比?

  • 因此,对于菜单A,我们将看到65%和38%;对于菜单B,我们将看到60%和35%最后,对于手册C,我们将看到45%和26%

我的数据:

manu <- c('A', 'A', 'A', 'B',"B", "C","C")
brand <- c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2")
vol <- c(10,    25, 30, 45, 15, 25, 20)

我的代码:

ggplot2::ggplot(environment=environment()) + ggplot2::geom_bar(ggplot2::aes(y = vol, x = manu, fill = brand), stat = "identity", position = ggplot2::position_stack(reverse = TRUE), data = df)

enter image description here

r ggplot2 bar-chart
2个回答
1
投票

这样的事情应该起作用。您必须按照自己的意愿四舍五入/使用百分比的位置。

install.packages("dplyr")
install.packages("magrittr")
library("magrittr")
library("dplyr")
library(ggplot2)


manu <- c('A', 'A', 'A', 'B',"B", "C","C")
brand <- c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2")
vol <- c(10,    25, 30, 45, 15, 25, 20)

df <- data.frame(manu = c('A', 'A', 'A', 'B',"B", "C","C"),
                 brand = c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2"),
                 vol = c(10, 25, 30, 45, 15, 25, 20))


df2 <- df %>% group_by(manu) %>% mutate(total_vol = sum(vol),
                                        percent_vol = vol/total_vol) %>%
          ungroup()

ggplot(data=df2) + 
     geom_bar(aes(x=manu, y=vol, fill=brand),stat = "identity",position = position_stack(reverse = TRUE)) +
     geom_text(aes(x=manu, y=vol, label=percent_vol),
              position = position_stack(vjust = .5)) +
     geom_text(aes(x = manu,y = 70, label = df2$total_vol))

enter image description here


0
投票

“道奇”不解决吗?

ggplot2::ggplot(environment=environment()) + ggplot2::geom_bar(ggplot2::aes(y = vol, x = manu, fill = brand), stat = "identity", position = "dodge", data = df)
© www.soinside.com 2019 - 2024. All rights reserved.