如何在ggplot2分组柱状图中修改指定日期对应柱的颜色?
给ggplot2分组柱状图的特定日期柱子设置特殊样式
需求:在分组(dodged)柱状图中,将日期为“Nov-24”对应的两个柱子与其他柱子区分开,可通过修改颜色或添加边框实现,以下是两种简便的实现方案:
方案1:修改目标柱子的填充色
通过给数据添加高亮标识列,结合event和标识列设置填充色,让目标柱子使用更深的同色系颜色,直观区分:
library(tidyr) library(ggplot2) # 原始数据 df <- data.frame(mat = c("Apr-24", "Nov-24", "Apr-25", "Nov-25", "Apr-26", "Sep-26", "Apr-27"), term_rv = c(0.14, 0.34, 0.19, 0.22, 0.34, 0.16, 0.27), zc_rv = c(0.12, 0.31, 0.23, 0.27, 0.36, 0.09, 0.29)) # 用pivot_longer替代gather(tidyr推荐的新版函数),转换为长格式 df2 <- pivot_longer(df, cols = term_rv:zc_rv, names_to = "event", values_to = "total") # 添加高亮标识:标记是否为Nov-24的行 df2$is_highlight <- ifelse(df2$mat == "Nov-24", "highlight", "normal") # 绘图 ggplot(df2, aes(x=mat, y=total, fill=interaction(event, is_highlight))) + geom_bar(width = 0.8, stat = "identity", position = 'dodge') + theme_bw() + scale_fill_manual(name = "Method", labels = c("TF", "TF(Nov-24)", "ZC", "ZC(Nov-24)"), values = c("#ff8080", "#cc0000", "#00cccc", "#009999")) + # 调整图例为两列,避免过长 guides(fill = guide_legend(ncol = 2))
方案2:给目标柱子添加高亮边框
如果不想修改填充色,给Nov-24的柱子添加粗边框是更简洁的方案,无需调整原有图例结构:
# 沿用上面处理好的df2数据 ggplot(df2, aes(x=mat, y=total, fill=event, color=is_highlight, size=is_highlight)) + geom_bar(width = 0.8, stat = "identity", position = 'dodge') + theme_bw() + scale_fill_manual(name = "Method", label = c("TF", "ZC"), values = c("#ff8080", "#00cccc")) + # 设置边框颜色:普通柱子黑色,目标柱子红色 scale_color_manual(values = c("normal" = "black", "highlight" = "red")) + # 设置边框粗细:普通柱子细,目标柱子粗 scale_size_manual(values = c("normal" = 0.5, "highlight" = 2)) + # 隐藏颜色和尺寸的冗余图例 guides(color = "none", size = "none")
两种方案都无需大幅改动原有代码,仅通过添加标识列和调整ggplot的美学映射即可实现需求。
内容的提问来源于stack exchange,提问作者Renegade_rm56
相关产品推荐
相关产品推荐

