我目前將 geom_text 設定為條形圖的中心...

enroll_bar <- enroll_cohort %>% filter(chrt_grad != 2013) %>%
mutate(college_enrolled = factor(college_enrolled),
chrt_grad = factor(chrt_grad)) %>%
mutate(label_height = cumsum(n)) %>%
ggplot()
geom_col(mapping = aes(x = chrt_grad, y = n, fill = fct_rev(college_enrolled)))
geom_text(aes(x = chrt_grad, y = label_height, label = n), color = "white",
position = position_stack(vjust = 0.5))
scale_y_continuous(expand = expansion(mult = c(0, 0.1)))
labs(x = NULL,
y = NULL)
scale_fill_manual(labels = c("Enrolled", "Not Enrolled"), values = c("#00aeff", "#005488"))
如何垂直對齊文本,以便將 geom_text 圖層設定在每個條的相同 y 軸位置?此外,有沒有辦法做到這一點,因此無論 y 軸的比例如何,文本始終對齊,因為這是一個引數化報告,并且 y 軸值隨每個報告而變化?
uj5u.com熱心網友回復:
if_else您可以使用(或case_when>2組)為每個組設定統一的標簽高度。對于單個圖,您可以簡單地設定一個值,例如label_height = if_else(college_enrolled == "Enrolled", 20000, 3000). 為了使多個繪圖的相對高度一致,您可以設定label_height為 y 軸范圍的比例:
library(tidyverse)
# make a fake dataset
enroll_cohort <- expand_grid(
chrt_grad = factor(2014:2021),
college_enrolled = factor(c("Enrolled", "Not Enrolled")),
) %>%
mutate(
n = sample(18000:26000, 16),
n = if_else(college_enrolled == "Enrolled", n, as.integer(n / 3))
)
enroll_bar <- enroll_cohort %>%
group_by(chrt_grad) %>% # find each bar's height by summing up `n`
mutate(bar_height = sum(n)) %>% # within each year
ungroup() %>%
mutate(label_height = if_else(
college_enrolled == "Enrolled",
max(bar_height) * .6, # axis height is max() of bar heights;
max(bar_height) * .1 # set label_height as % of axis height
)) %>%
ggplot()
geom_col(aes(x = chrt_grad, y = n, fill = college_enrolled), color = NA)
geom_text(
aes(x = chrt_grad, y = label_height, label = n),
color = "white"
)
scale_y_continuous(expand = expansion(mult = c(0, 0.1)))
labs(x = NULL, y = NULL)
scale_fill_manual(values = c("#00aeff", "#005488"))
如果我們生成另一個具有不同n值范圍的資料集——例如,~1200 - ~2000——文本標簽保持在相同的相對位置:

uj5u.com熱心網友回復:
如果您希望標簽處于統一的高度,您可以在您要查找的高度指定一個yingeom_text()外。aes
我使用了資料集diamonds。列太不均勻,無法看到白色文本,因此我將頂部標簽更改為黑色。
因為底部組的最小值非常低,所以我將其設定為 100。頂部組設定為 5000。本質上,我創建了一個向量——100、5000、100、5000、100... 等等,使用rep()(重復)。
資料的設定方式不同,因為您沒有將其包含在問題中。不過,這應該沒關系。
圖書館(tidyverse)
diamonds %>%
filter(color %in% c("E", "I")) %>%
ggplot(aes(x = cut,
fill = color))
geom_bar()
geom_text(aes(label = ..count..), # use the count
y = rep(c(100, 5000), # btm label y = 100, top label y = 5K
times = 5),
stat = 'count',
color = rep(c("white", "black"), # btm label white, top black
times = 5),
position = position_stack(vjust = .5))
scale_y_continuous(expand = expansion(mult = c(0, 0.1)))
labs(x = NULL, y = NULL)
scale_fill_manual(labels = c("E", "I"),
values = c("#00aeff", "#005488"))
theme_bw()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/430663.html
下一篇:圖表未出現
