gpt4 book ai didi

r - ggplot2::position_stack 中的距离是如何缩放的?

转载 作者:行者123 更新时间:2023-12-01 13:20:36 26 4
gpt4 key购买 nike

我想在 ggplot 的堆叠条旁边绘制一个带有标签的人口金字塔。我使用 position_stack(vjust=1.3) 使用下面的代码让标 checkout 现在条形的“顶部”旁边,但我不明白该命令如何缩放标签的位置。

library(tidyverse)

data.frame(
sex = c("F", "F", "F", "F", "F", "F", "F", "F", "M", "M", "M", "M", "M", "M", "M", "M"),
ag = c("0-9", "10-19", "20-29", "30-39", "40-49", "50-59", "60-69", "70+"),
n = c(-0.21, -0.12, -0.09, -0.03, -0.04, -0.01, 0, 0, 0.22, 0.11, 0.06, 0.04, 0.02, 0.03, 0.01, 0),
stringsAsFactors = F
) %>%
ggplot(aes(x=ag, y = n, fill=sex)) +
geom_col() +
scale_fill_brewer("",labels = c("Women", "Men"), palette = "Set1") +
coord_flip() +
geom_text(data = . %>% dplyr::filter(sex == "M"),
aes(label = n),
position=position_stack(vjust=1.3)) +
geom_text(data = . %>% dplyr::filter(sex == "F"),
aes(label = n),
position=position_stack(vjust=-0.3))

在结果图中,标签与条形上边缘的距离不等。我希望标签整齐地出现在每个栏的旁边。 enter image description here

最佳答案

你可以试试position_nudge

   df %>% 
{ggplot(data=.,aes(x=ag, y = n, fill=sex,label = n)) +
geom_col() +
geom_text(position = position_nudge(y = ifelse(.$sex == "F", -0.02, 0.02)))+
coord_flip()}

enter image description here

关于r - ggplot2::position_stack 中的距离是如何缩放的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com