簡體   English   中英

如何在 ggplot2 中按組顯示匯總統計信息

[英]How to display summary statistics by group in ggplot2

我有一個包含 3 個變量的數據框:manu、brand 和 vol。

這是我的 plot。 如何在 plot 的某處按制造商顯示總體積和體積百分比?

  • 因此,對於手冊 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)

在此處輸入圖像描述

完成的最終答案:

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))

df$grand_total_vol = sum(df$vol)

df2 <- df %>% group_by(manu) %>% mutate(total_vol = sum(vol)) %>% mutate(percent_vol = 100*total_vol/grand_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= paste0("Percent Vol: ", round(percent_vol*100,1),"%")),
            position = position_stack(vjust = .5)) +
  geom_text(aes(x = manu,y = 70, label = paste0(df2$total_vol, "; ", round(df2$percent_vol, 1), "%")))

像這樣的東西應該工作。 您將不得不根據您認為合適的百分比計算/使用 position。

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= paste0("Percent Vol: ", round(percent_vol*100,1),"%")),
              position = position_stack(vjust = .5)) +
     geom_text(aes(x = manu,y = 70, label = paste0("Total Vol: ",df2$total_vol)))

已編輯

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM