簡體   English   中英

顯示ggplot2中geom_bar頂部的總百分比,同時顯示y軸上的計數

[英]Show percent of total on top of geom_bar in ggplot2 while showing counts on y axis

我正在嘗試使用ggplot2創建條形圖,顯示y軸上的計數,但也顯示每個條形頂部的總計百分比。 我已經計算了總數的計數和百分比,但無法弄清楚如何在條形圖的頂部添加百分比。 我正在嘗試使用geom_text,但無法使其正常工作。

一個最小的例子:

iris %>% 
  group_by(Species) %>% 
  summarize(count = n()) %>% 
  mutate(percent = count/sum(count)) %>% 
  ggplot(aes(x=Species, y=count)) +
    geom_bar(stat="identity") + 
    geom_text(aes(label = scales::percent(..prop..), y=..count..), stat= "count", vjust = -.5)

我看過其他答案,例如如何在百分比條形圖上方添加百分比或計數標簽? ,但在這些示例中,y軸和標簽都顯示百分比。 我試圖顯示y軸上的計數和標簽中的百分數。

只需使用percent作為標簽。

iris %>% 
  group_by(Species) %>% 
  summarize(count = n()) %>% 
  mutate(percent = count/sum(count)) %>% 
  ggplot(aes(x=Species, y=count)) +
  geom_col() +
  geom_text(aes(label = paste0(round(100 * percent, 1), "%")), vjust = -0.25)

在此輸入圖像描述

library(dplyr)
library(ggplot2)
df1 = iris %>% 
    group_by(Species) %>% 
    summarize(count = n()) %>% 
    mutate(percent = count/sum(count))
ggplot(data = df1, aes(x = Species, y = count, label = paste0(round(percent,2),"%"))) +
    geom_bar(stat="identity") +
    geom_text(aes(y = count*1.1))

暫無
暫無

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

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