我一直試圖在每個欄的頂部添加一個標簽,以代表每個種族在推薦中的比例。
由于某種原因,我無法將標簽放置在每個欄的頂部。我該如何解決?
我的代碼如下
freq <- df %>%
group_by(ethnicity) %>%
summarise(n = n()) %>%
mutate(f = round((n/sum(n)*100, 1))
df %>%
group_by(pathway) %>%
count(ethnicity) %>%
ggplot(aes(x = ethnicity, y = n , fill = pathway))
geom_bar(stat = "identity", position = "stack")
geom_text(data = freq,
aes(x= ethnicity, y = f, label = f),
inherit.aes = FALSE)
theme(legend.position = "bottom")
scale_fill_manual(name = "",
values = c("light blue", "deepskyblue4"),
labels = "a", "b")
xlab("")
ylab("Number of Referrals")
scale_y_continuous(breaks = seq(0, 2250, 250), expand = c(0,0)
這是它目前的樣子

uj5u.com熱心網友回復:
由于您使用計數作為您的 y 軸位置geom_bar,因此您需要在您的中使用相同的東西geom_text來將標簽放在正確的位置。下面是使用mtcars資料集的示例。使用vjust = -1我在標簽和條之間留了一點空間,使其更清晰和美觀。
library(tidyverse)
mtcars %>%
group_by(carb) %>%
summarise(n = n()) %>%
mutate(f = round(proportions(n) * 100, 1)) -> frq
mtcars %>%
group_by(gear) %>%
count(carb) -> df
df %>%
ggplot(aes(x = carb, y = n, fill = gear))
geom_bar(stat = "identity", position = "stack")
geom_text(data = frq,
vjust = -1,
aes(x= carb, y = n, label = f),
inherit.aes = FALSE)

由reprex 包于 2022-10-31 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/523677.html
