如何在ggplot的geom_point旁显示数值并修改图例标题?
解决方案
1. 给数据点添加数值标注
用geom_text()或geom_label()就能实现——前者是纯文本标注,后者带背景框,按需选就行。在aes()里指定label为你要显示的百分比列,再通过vjust、hjust调整标注位置,避免和点重叠。
2. 修改图例标题
直接在scale_color_manual()里加name参数,或者用labs(color="新标题"),两种方式都能改。
另外提个小细节:ggplot的aes()里不用写datacombined$列名,直接写列名更简洁规范。
修改后的完整代码如下:
ggplot(datacombined, aes(x = `Poulation group`, y = `Percent of population in cicilian labor force`, color = Location)) + geom_point(size=4) + # 添加数值标注,向上偏移避免遮挡点 geom_text(aes(label = `Percent of population in cicilian labor force`), vjust = -0.8, size = 3.5) + scale_color_manual(name = "地区", # 这里修改图例标题 values = c("US" = "darkblue", "OH" = "red")) + ylim(0,100)+ theme_bw()+ ylab("Percentage of population in civilian labour force") + xlab("Population group")
如果觉得纯文本标注容易和背景混,换成geom_label()即可:
geom_label(aes(label = `Percent of population in cicilian labor force`), vjust = -1, size = 3, fill = "white")
内容的提问来源于stack exchange,提问作者tonjekm
相关产品推荐
相关产品推荐

