如果我將你的問題與你給出的鏈接進行比較,那麼區別在於鏈接「自我計數」。這就是我所做的。我不確定這是否適合您的真實數據。
library(ggplot2)
library(dplyr)
mpg %>%
mutate(manufacturer = as.factor(manufacturer),
class = as.factor(class)) %>%
group_by(manufacturer, class) %>%
summarise(count_class = n()) %>%
group_by(manufacturer) %>%
mutate(count_man = sum(count_class)) %>%
mutate(percent = count_class/count_man * 100) %>%
ggplot() +
geom_bar(aes(x = manufacturer,
y = count_man,
group = class,
fill = class),
stat = "identity") +
geom_text(aes(x = manufacturer,
y = count_man,
label = sprintf("%0.1f%%", percent)),
position = position_stack(vjust = 0.5))
編輯,基於註釋:
我犯了一個錯誤的選擇了錯誤的列y
library(ggplot2)
library(dplyr)
mpg %>%
mutate(manufacturer = as.factor(manufacturer),
class = as.factor(class)) %>%
group_by(manufacturer, class) %>%
summarise(count_class = n()) %>%
group_by(manufacturer) %>%
mutate(count_man = sum(count_class)) %>%
mutate(percent = count_class/count_man * 100) %>%
ungroup() %>%
ggplot(aes(x = manufacturer,
y = count_class,
group = class)) +
geom_bar(aes(fill = class),
stat = "identity") +
geom_text(aes(label = sprintf("%0.1f%%", percent)),
position = position_stack(vjust = 0.5))
你的方法,百分比是正確的,但塊大小是錯誤的。但我認爲這是正確的方向;讓我和dplyr一起玩,看看我能否做對。 – kraussian
我是多麼愚蠢!我也會看看並編輯答案! – ricoderks
哇,現在完美了!我也想過這樣做,但沒有意識到可以使用_ungroup_將彙總數據恢復爲原始格式。這是我的缺失環節;謝謝! :) – kraussian