如何为geom_histogram添加独立于x/y美学的球员排名标签?
问题
我需要绘制MLB各队在Baseball America百大新秀榜单中的新秀数量,数据包含Organization(球队)、Player(球员)、Rank(排名)、Total(该队新秀总数)、Count(计数)字段。以波士顿红袜队为例,数据如下:
BA_100 <- data.frame(Organization = c("BOS", "BOS", "BOS", "BOS"), Player = c("Marcelo Mayer", "Roman Anthony", "Kyle Teel", "Ceddanne Rafaela"), Rank = c(14, 21, 62, 94), Total = c(4, 4, 4, 4), Count = c(1, 1, 1, 1))
我希望按各队新秀数量降序排列x轴的球队,当前已用以下代码绘制出红袜队的柱状图:
library(tidyverse) library(mlbplotr) library(ggtext) BA_100 %>% filter(Organization == "BOS") %>% ggplot(aes(x = fct_reorder(Organization, desc(Total)), y = Count, color = Organization, fill = Organization)) + geom_histogram(stat = "identity") + scale_fill_mlb(type = "primary") + scale_color_mlb(type = "secondary") + labs(title = "Number of Ranked Prospects (**Baseball America**)", x = NULL, y = "Count", fill = NULL) + theme_classic() + theme(plot.title = element_markdown(hjust = 0.5), axis.text.x = element_mlb_scoreboard_logo(size = 0.8), axis.ticks.x = element_blank(), legend.position = "bottom", legend.text = element_text(face = "bold"), plot.caption = element_text(face = "bold"))
现在需要在每个条形的分段中添加对应球员的排名(即14、21、62、94),尝试过stat_bin()、geom_label()、geom_text()均未成功,遇到x/y美学映射相关错误,求解决方法。
解决方法
问题出在堆叠条形时,没有给文本元素指定正确的位置映射。推荐用geom_col替代geom_histogram(stat="identity")(功能一致但更适合已知数值的场景),再通过position_stack()定位每个排名文本的位置,确保每个排名对应到堆叠的单个分段中。
修改后的完整代码如下:
library(tidyverse) library(mlbplotr) library(ggtext) BA_100 %>% filter(Organization == "BOS") %>% ggplot(aes(x = fct_reorder(Organization, desc(Total)), y = Count, color = Organization, fill = Organization)) + # 用geom_col替代geom_histogram,代码可读性更强 geom_col() + # 添加排名文本,position_stack确保文本居中对齐到对应分段 geom_text(aes(label = Rank), position = position_stack(vjust = 0.5), color = "white", # 白色文本与球队填充色形成对比,保证可读性 fontface = "bold") + scale_fill_mlb(type = "primary") + scale_color_mlb(type = "secondary") + labs(title = "Number of Ranked Prospects (**Baseball America**)", x = NULL, y = "Count", fill = NULL) + theme_classic() + theme(plot.title = element_markdown(hjust = 0.5), axis.text.x = element_mlb_scoreboard_logo(size = 0.8), axis.ticks.x = element_blank(), legend.position = "bottom", legend.text = element_text(face = "bold"), plot.caption = element_text(face = "bold"))
关键说明
- 替换
geom_histogram为geom_col:两者在stat="identity"时效果相同,但geom_col专门用于绘制基于已有数值的柱状图,逻辑更清晰。 - 文本位置控制:
position = position_stack(vjust = 0.5)让每个排名文本自动对齐到对应分段的垂直中心,解决了之前的位置映射错误。 - 文本颜色优化:设置
color = "white"确保文本在球队颜色上清晰可见,也可根据球队主色调调整为其他对比色。
如果后续扩展到多队数据,fct_reorder(Organization, desc(Total))会自动按各队新秀总数降序排列x轴球队,无需额外调整。
内容的提问来源于stack exchange,提问作者stevoo_p13
相关产品推荐
相关产品推荐

