向 geom_bar 添加标签

问题描述 投票:0回答:1

我对这个chart的标签有一些困难。具体来说,标签不适合其相应的栏。另外,标签似乎位置不正确。换句话说,非西班牙裔白人的百分比应出现在橙色框中。

谢谢,

MRR

IDD_line_race <-
  ggplot(race_2010, aes(x =Year_  , y =per_X_ , fill=race_new2), colour="black",
         stat="identity", width=0.9,  position = position_dodge()) +
  geom_col() +
  geom_text(aes(y = per_X_, label = paste0(format(per_X_),"%")), colour = "white")+
  scale_fill_manual(values=c("#F76900","#000E54")) + 
  labs(
    x = "Year",
    y = "Population 65+ (%)",
    caption = (""),
    face = "bold"
  ) +
  theme_classic()+
  coord_flip()

IDD_line_race
r ggplot2 geom-bar geom-text
1个回答
1
投票

问题是

geom_col
默认使用
position = "stack"
,而
geom_text
使用
position="identity"
。要将标签放在正确的位置,您必须使用
position = "stack"
或更详细的
position = position_stack()
中的
geom_text
。此外,我使用
hjust=1
右对齐标签,并消除了
ggplot()
调用中的混乱。

使用一些虚假的示例数据:;

library(ggplot2)

set.seed(123)

race_2010 <- data.frame(
  Year_ = rep(2010:2019, 2),
  race_new2 = rep(c("non-Hispanic Black", "non-Hispanic White"), each = 10),
  per_X_ = round(c(runif(10, 1, 2), runif(10, 9, 12)), 1)
)

ggplot(race_2010, aes(x =Year_  , y =per_X_ , fill=race_new2)) +
  geom_col() +
  geom_text(aes(y = per_X_, label = paste0(format(per_X_),"%")), colour = "white", position = position_stack(), hjust = 1) +
  scale_fill_manual(values=c("#F76900","#000E54")) + 
  labs(
    x = "Year",
    y = "Population 65+ (%)",
    caption = (""),
    face = "bold"
  ) +
  theme_classic()+
  coord_flip()

© www.soinside.com 2019 - 2024. All rights reserved.