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

ggplot2中geom_path图的图例标签优化与调色板调整方法

优化图例标识与配色方案

针对你的需求,这里提供两个关键修改点的实现方式:

1. 将图例标识改为填充方形

因为你使用的是geom_path,默认图例显示的是线条样式。要改成清晰的填充方形,需要通过guides()函数覆盖图例的默认美学参数,把线条替换为填充方块:

  • 使用shape = 22指定带边框的填充方形(若要纯填充方形可改用shape = 15)
  • 关闭图例中的线条显示(linetype = 0)
  • 为方形设置对应颜色的填充,同时增大标识尺寸提升可见度

2. 更换高辨识度配色方案

推荐几种实用的离散配色方案:

  • 色盲友好型:scale_color_viridis_d(),适配所有视觉人群,色彩过渡自然且区分度高
  • 经典分类配色:scale_color_brewer(palette = "Set1"),对比度强,适合分组展示
  • 自定义配色:scale_color_manual(values = c("#E69F00", "#56B4E9", "#009E73")),可根据需求自行指定颜色

修改后的完整代码

# Load required library
library(ggplot2)
library(ggmulti)

# Simulate data
set.seed(123)  # Set a seed for reproducibility
n_points <- 100  # Number of data points

# Simulate values for Loading variables l1, l2, l3, l4, l5, and l6
l1 <- rnorm(n_points)
l2 <- rnorm(n_points)
l3 <- rnorm(n_points)
l4 <- rnorm(n_points)
l5 <- rnorm(n_points)
l6 <- rnorm(n_points)

# Create a labelling variable with categories
labelling <- factor(sample(1:3, n_points, replace = TRUE))
# 给类别添加直观名称,优化图例标签可读性
levels(labelling) <- c("Group A", "Group B", "Group C")

# Create a data frame with the simulated data
dataplot <- data.frame(l1, l2, l3, l4, l5, l6, labelling)

# Create the plot using ggplot
p <- ggplot(dataplot,
            aes(
              Loading1 = l1,
              Loading2 = l2,
              Loading3 = l3,
              Loading4 = l4,
              Loading5 = l5,
              Loading6 = l6,
              color = labelling
            )) +
  geom_path(alpha = 0.2) +
  theme_bw() +
  # 使用色盲友好的viridis配色方案
  scale_color_viridis_d(option = "plasma") +
  # 修改图例为填充方形并提升可见度
  guides(color = guide_legend(
    override.aes = list(
      shape = 22,
      fill = scales::viridis_pal(option = "plasma")(3),
      linetype = 0,
      size = 4
    )
  )) +
  coord_serialaxes()

# Display the plot
print(p)

额外说明

  • 若想切换配色,只需替换scale_color_viridis_d():比如改用scale_color_brewer(palette = "Set1"),或自定义的scale_color_manual(values = c("red", "blue", "green"))
  • 调整size参数可以改变图例方块的大小,按需适配图表尺寸

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:57:34