You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言使用ggplot绘制柱状图时如何高亮湿度最高的前3个柱子?

R ggplot高亮柱状图Top3柱子解决方案

你可以通过新增分类标识列、映射填充色的方式实现需求,具体操作如下:

步骤1:给数据集增加高亮标识列

推荐使用dplyr处理,代码如下:

library(dplyr)
library(ggplot2)
library(ggpubr) # 加载theme_pubclean所属依赖包

# 新增字段标记湿度排名前3的月份
df_hum <- df_hum %>%
  mutate(is_top3 = rank(-humidity_perc) <= 3)

如果不想引入dplyr依赖,也可以用基础R语法实现:

df_hum$is_top3 <- rank(-df_hum$humidity_perc) <= 3

步骤2:修改绘图代码映射填充色

将原来geom_bar的固定填充色改为映射到新增的标识列,再手动指定两组颜色即可:

ggplot(df_hum, aes(x = month, y = humidity_perc)) +
  geom_bar(aes(fill = is_top3), stat = "identity") +
  geom_text(aes(label = humidity_perc), vjust = -0.3) +
  # 手动设置填充色:非Top3沿用原蓝色,Top3改为黄色高亮(可自行替换色值)
  scale_fill_manual(
    values = c("TRUE" = "#EFC000FF", "FALSE" = "#0073C2FF"),
    guide = "none" # 不需要显示图例可加这行隐藏
  ) +
  theme_pubclean()

可选扩展:3个高亮柱子使用不同颜色

如果需要给Top1/Top2/Top3设置不同的高亮色,可调整标识列逻辑:

# 生成分级标识列
df_hum <- df_hum %>%
  mutate(
    hum_rank = rank(-humidity_perc),
    fill_group = case_when(
      hum_rank == 1 ~ "top1",
      hum_rank == 2 ~ "top2",
      hum_rank == 3 ~ "top3",
      TRUE ~ "others"
    )
  )

# 绘图时手动指定4组颜色即可
ggplot(df_hum, aes(x = month, y = humidity_perc)) +
  geom_bar(aes(fill = fill_group), stat = "identity") +
  geom_text(aes(label = humidity_perc), vjust = -0.3) +
  scale_fill_manual(
    values = c(
      "top1" = "#CD534CFF",
      "top2" = "#EFC000FF",
      "top3" = "#868686FF",
      "others" = "#0073C2FF"
    ),
    guide = "none"
  ) +
  theme_pubclean()

内容的提问来源于stack exchange,提问作者Embargo96

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:45:02