我有一個資料集,其中包含變數“SEXO”(M 或 F)和“Class”(0 或 1)。我想使用 ggplot2 創建一個條形圖,以百分比形式顯示每種性別的類分布。我能夠得到情節,但我似乎無法讓標簽本身在酒吧上作業。我不想更改軸上的標簽,我只想獲得每個 SEXO 的圖上顯示的百分比。
這是我一直在使用的代碼:
ggplot(data = df, aes(x = SEXO, fill = Class)) geom_bar(position = 'fill')
我還附上了代碼生成的圖的影像:

這將是理想的結果:

uj5u.com熱心網友回復:
這是一個使用mtcars資料集的示例,您可以在其中計算每組的百分比,并使用這些來放置在您的條形圖中,使用label如下geom_text所示:
library(ggplot2)
library(dplyr)
mtcars %>%
group_by(am, vs) %>%
summarise(cnt = n()) %>%
mutate(perc = round(cnt/sum(cnt), 2)) %>%
ggplot(aes(x = factor(vs), fill = factor(am), y = perc))
geom_col(position = 'fill')
geom_text(aes(label = paste0(perc*100,"%"), y = perc), position = position_stack(vjust = 0.5), size = 3)
labs(fill = 'Class', x = 'vs')
scale_y_continuous(limits = c(0,1))
#> `summarise()` has grouped output by 'am'. You can override using the `.groups`
#> argument.

使用reprex v2.0.2創建于 2022-11-02
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/527530.html
標籤:rggplot2
