[英]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.