簡體   English   中英

向 geom_bar 添加標簽

[英]Adding labels to the geom_bar

我對這張圖表的標簽有些困難。 具體來說,標簽不適合其相應的欄。 此外,看起來標簽不在正確的位置。 換句話說,非西班牙裔白人的百分比應該出現在橙色框中。

謝謝,

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

問題是geom_col默認使用position = "stack"geom_text使用position="identity" 要將標簽放在正確的位置,您必須在 geom_text 中使用position = "stack"或更詳細的geom_text position = position_stack() 此外,我使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM