简体   繁体   English

向 geom_bar 添加标签

[英]Adding labels to the geom_bar

I have some difficulties with the labels for this chart .我对这张图表的标签有些困难。 Specifically, the labels do not fit in their corresponding bar.具体来说,标签不适合其相应的栏。 Also, it looks like the labels are not in a right place.此外,看起来标签不在正确的位置。 In other words, the percentage for non-Hispanic Whites should appear in the orange boxes.换句话说,非西班牙裔白人的百分比应该出现在橙色框中。

Thanks,谢谢,

MRR 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

The issue is that geom_col by default uses position = "stack" while geom_text uses position="identity" .问题是geom_col默认使用position = "stack"geom_text使用position="identity" To put your labels at the correct positions you have to use position = "stack" or the more verbose position = position_stack() in geom_text too.要将标签放在正确的位置,您必须在 geom_text 中使用position = "stack"或更详细的geom_text position = position_stack() Additionally I right aligned the labels using hjust=1 and removed the clutter from the ggplot() call.此外,我使用hjust=1右对齐标签,并从ggplot()调用中删除了混乱。

Using some fake example data:;使用一些假的示例数据:;

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM