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

如何在ggplot的geom_bar中高亮指定国家条形且不影响图例

解决方案:高亮ggplot柱状图中的特定国家条形

这里提供两种不影响原有图例的高亮方案,分别是添加独特边框和加深填充颜色,适配你的需求:

方法1:添加加粗边框高亮

通过给目标国家的条形设置更粗的深色边框,既醒目又不会干扰原有的年份图例:

library(ggplot2)
library(dplyr)
library(haven)

Panel <- read_dta("http://dss.princeton.edu/training/Panel101.dta")
Panel$y = Panel$y / 1000000

# 创建高亮标识:标记C国
Panel <- Panel %>% mutate(is_highlight = country == "C")

Panel %>%
  filter(year %in% c(1990, 1991)) %>% 
  ggplot(aes(x = country, y = y, fill = as.factor(year))) +
  geom_bar(
    stat = 'identity',
    position = 'dodge2',
    # 根据高亮状态设置边框的粗细和颜色
    aes(size = is_highlight, colour = is_highlight)
  ) +
  # 手动设置边框参数,并隐藏这两个参数的图例
  scale_size_manual(values = c(0.5, 2), guide = "none") +
  scale_colour_manual(values = c("white", "black"), guide = "none") +
  scale_fill_manual(values = c('#001d87', '#d9912e')) +
  labs(fill = 'Year', x = 'Country') +
  theme_classic()

方法2:加深填充颜色高亮

如果希望通过颜色深浅区分,可基于原有年份颜色加深目标国家的条形,同时保持图例不变:

library(ggplot2)
library(dplyr)
library(haven)
library(colorspace) # 用于调整颜色深浅

Panel <- read_dta("http://dss.princeton.edu/training/Panel101.dta")
Panel$y = Panel$y / 1000000

# 定义基础颜色和加深后的颜色
base_colors <- c('#001d87', '#d9912e')
darkened_colors <- darken(base_colors, amount = 0.3) # 加深30%

Panel %>%
  filter(year %in% c(1990, 1991)) %>% 
  mutate(is_highlight = country == "C") %>%
  ggplot(aes(
    x = country, y = y,
    # 用年份+高亮状态的组合作为填充映射依据
    fill = interaction(as.factor(year), is_highlight)
  )) +
  geom_bar(stat = 'identity', position = 'dodge2', colour = 'white') +
  scale_fill_manual(
    values = c(
      `1990.FALSE` = base_colors[1], `1990.TRUE` = darkened_colors[1],
      `1991.FALSE` = base_colors[2], `1991.TRUE` = darkened_colors[2]
    ),
    # 调整图例:只保留年份分类,隐藏高亮状态
    breaks = c("1990.FALSE", "1991.FALSE"),
    labels = c("1990", "1991"),
    name = "Year"
  ) +
  labs(x = 'Country') +
  theme_classic()

注意事项

  • 方法1无需额外依赖包,实现简单;方法2需要colorspace包,可通过install.packages("colorspace")安装。
  • 若要高亮其他国家,只需修改country == "C"中的国家代码即可。

内容的提问来源于stack exchange,提问作者Nuñes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 13:47:43