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

如何为ggplot2散点图中指定站点的图形添加黑色轮廓?

ggplot2散点图:指定站点添加黑色轮廓并保留原有颜色

初始实现

我用ggplot2绘制散点图,通过形状和颜色区分不同站点(Site),初始代码及效果如下:

all <- ggplot(data = all_quantity, aes(x=Distance, y=Quantity, shape=Site, colour=Site)) +
  geom_point(size=3) + # 设置点大小
  scale_y_continuous(limits = c(0, 80), breaks = c(0, 10, 20, 30, 40, 50, 60, 70, 80)) + # Y轴刻度
  scale_x_continuous(limits = c(0, 30), breaks = c(0, 5, 10, 15, 20, 25, 30)) + # X轴刻度
  labs(y="Quantity (pg/mL)", x="Downstream Distance (km)")
all

初始散点图

需求与问题

我希望给Belton、Bridgeport、Canyon这三个站点的点添加黑色轮廓,避免颜色混杂难以区分。尝试了以下代码:

all <- ggplot(data = all_quantity, aes(x=Distance, y=Quantity, shape=Site, fill=Site)) +
  geom_point(size=3, colour="black") +
  scale_shape_manual(values = c(21, 24, 22, 3, 7, 8)) +
  scale_y_continuous(limits = c(0, 80), breaks = c(0, 10, 20, 30, 40, 50, 60, 70, 80)) + # Y轴刻度
  scale_x_continuous(limits = c(0, 30), breaks = c(0, 5, 10, 15, 20, 25, 30)) + # X轴刻度
  labs(y="Quantity (pg/mL)", x="Downstream Distance (km)")
all

尝试后的散点图

这段代码实现了目标站点的黑色轮廓,但Lewisville、Stillhouse、Worth三个站点的颜色变成了黑色,无法保留初始图中的原有颜色。

解决方案

核心思路是区分带填充的形状(如21、24、22,支持fill和colour分别设置填充色与轮廓色)和无填充的形状(如3、7、8,仅受colour控制),针对两类站点分别设置颜色参数:

# 定义站点对应的形状与颜色(颜色匹配初始ggplot默认配色)
site_shapes <- c(
  "Belton" = 21, "Bridgeport" = 24, "Canyon" = 22,
  "Lewisville" = 3, "Stillhouse" = 7, "Worth" = 8
)
site_colors <- c(
  "Belton" = "#F8766D", "Bridgeport" = "#00BA38", "Canyon" = "#619CFF",
  "Lewisville" = "#F8766D", "Stillhouse" = "#00BA38", "Worth" = "#619CFF"
)

all <- ggplot(data = all_quantity, aes(x=Distance, y=Quantity)) +
  # 针对不同站点设置填充、轮廓和形状
  geom_point(size=3,
             aes(
               shape = Site,
               # 目标站点用黑色轮廓,其他站点用自身颜色
               colour = ifelse(Site %in% c("Belton", "Bridgeport", "Canyon"), "black", Site),
               # 目标站点设置填充色,其他站点无需填充
               fill = ifelse(Site %in% c("Belton", "Bridgeport", "Canyon"), Site, NA)
             )) +
  # 手动指定形状、颜色和填充
  scale_shape_manual(values = site_shapes) +
  scale_colour_manual(values = c("black" = "black", site_colors)) +
  scale_fill_manual(values = site_colors, guide = "none") +
  # 保留原有的轴设置和标签
  scale_y_continuous(limits = c(0, 80), breaks = c(0, 10, 20, 30, 40, 50, 60, 70, 80)) +
  scale_x_continuous(limits = c(0, 30), breaks = c(0, 5, 10, 15, 20, 25, 30)) +
  labs(y="Quantity (pg/mL)", x="Downstream Distance (km)", shape="Site")
all

说明

  1. 带填充的形状(21、24、22)会显示填充色(fill)+黑色轮廓(colour),完美实现目标站点的效果;
  2. 无填充的形状(3、7、8)仅受colour控制,直接使用站点原有颜色,和初始图保持一致;
  3. 通过scale_colour_manual和scale_fill_manual统一颜色,确保配色和初始图匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:35:36