如何在ggplot柱状图中添加趋势线并高亮GoDigit?
问题:如何在ggplot柱状图中添加趋势线并高亮GoDigit?
背景
已通过ggplot生成保险公司分年度保费的分组柱状图,需完成两个优化:
- 为每个保险公司添加跨年度的趋势连线
- 高亮显示"GoDigit"对应的柱状条目
现有代码:
Recreated_figure_DHRP %>% ggplot(aes(x = Insurers, y =`INR BN`,fill = FY,group=FY)) + geom_bar(stat = "identity", position = position_dodge(), alpha = 0.75,)+ theme(axis.text.x = element_text(angle = 60, hjust = 1)) + theme(legend.position="top") + ylim(0,400)+ geom_text(aes(label = `INR BN`), fontface = "bold", vjust = 1.5, position = position_dodge(.9), size = 2.25)
解决方案
1. 添加跨年度趋势线
趋势线需要按**保险公司(Insurers)**分组,连接同一公司不同年度的数值点。在现有代码中添加geom_line和geom_point,注意重新指定group参数:
# 新增趋势线和数据点 geom_line(aes(group = Insurers), color = "darkslategray", size = 1, position = position_dodge(.9)) + geom_point(aes(group = Insurers), color = "darkslategray", size = 2, position = position_dodge(.9))
position = position_dodge(.9)保证线和点与柱状图的分组位置对齐- 调整
color和size参数可匹配目标图的样式
2. 高亮GoDigit条目
可以通过给GoDigit的柱状图添加红色边框实现高亮,在geom_bar之后新增一个针对GoDigit子集的图层:
# 高亮GoDigit的柱子 geom_bar(data = subset(Recreated_figure_DHRP, Insurers == "GoDigit"), stat = "identity", position = position_dodge(), color = "red", size = 1.2, fill = NA)
fill = NA保留原有填充色,只显示边框- 若需要改变填充色,可替换
fill为指定颜色(如fill = "#ffcccc")
完整代码
Recreated_figure_DHRP %>% ggplot(aes(x = Insurers, y =`INR BN`,fill = FY,group=FY)) + # 基础柱状图 geom_bar(stat = "identity", position = position_dodge(), alpha = 0.75)+ # 高亮GoDigit geom_bar(data = subset(Recreated_figure_DHRP, Insurers == "GoDigit"), stat = "identity", position = position_dodge(), color = "red", size = 1.2, fill = NA)+ # 趋势线和点 geom_line(aes(group = Insurers), color = "darkslategray", size = 1, position = position_dodge(.9))+ geom_point(aes(group = Insurers), color = "darkslategray", size = 2, position = position_dodge(.9))+ # 原有样式设置 theme(axis.text.x = element_text(angle = 60, hjust = 1)) + theme(legend.position="top") + ylim(0,400)+ geom_text(aes(label = `INR BN`), fontface = "bold", vjust = 1.5, position = position_dodge(.9), size = 2.25)
内容的提问来源于stack exchange,提问作者Jimi13 ABC
相关产品推荐
相关产品推荐

