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

使用ggnewscale时,如何移除ggplot散点图Project Performance图例中的黑点?

解决方法

要移除“Project Performance”图例中的黑点,只保留对应颜色的线型和标签,你需要做两处关键调整:

  • 第一个geom_point()(绘制基础散点)默认会生成图例元素,它会和geom_vline的图例合并,导致出现黑点。给这个geom_point()加上show.legend = FALSE,让它不参与图例生成。
  • 通过guides()函数指定“Project Performance”图例的样式,强制隐藏点符号。

修改后的完整代码如下:

#sample data
df <- data.frame(cohort=c("20-21","20-21","20-21","20-21","21-22","21-22","21-22","21-22","22-23","22-23","22-23","22-23"),
                 sat=c(1220, 1020, 850, 1160, 920, 970, 1170, 830, 730, 1200, 1090, 880),
                 project=c(2.5, 2.2, 2.6, 2.8, 2.9, 3.0,3.0, 2.8, 2.0, 2.5, 1.8, 2.0),
                 pass_sat=c("Met Threshold", "Met Threshold", "Did Not Meet Threshold", "Did Not Meet Threshold",
                            "Met Threshold", "Did Not Meet Threshold", "Did Not Meet Threshold","Met Threshold",
                            "Met Threshold", "Did Not Meet Threshold", "Did Not Meet Threshold","Met Threshold"))

threshold <- data.frame(x = c(2, 2.7), group = c("pass", "scholarship eligible"),
                        color = c("red", "darkgreen"), line=c("dashed", "solid"), stringsAsFactors = FALSE) 

group.colors <- c("Overall" ="#FFD580", "ELA" = "#CBC3E3", "Math" = "lightyellow", "Essential Skills"="lightpink")

#sample plot
#total sat against total project score 
ggplot(df, aes(x = project, y = sat)) + 
  geom_point(show.legend = FALSE) +  # 隐藏基础散点的图例元素
  facet_grid(.~cohort) +
  scale_x_continuous(limits = c(1, 3), breaks = seq(1, 3, by = 0.5)) +
  geom_smooth(method = "lm", se = F) +
  labs(x = "Total Project score", y = "Total SAT") + 
  stat_cor(method = "pearson", size = 2.6, digits= 2) +
  geom_vline(
    aes(xintercept = x, colour = group, linetype = group),
    threshold
  )+ 
  scale_linetype_manual(
    name = "Project Performance",
    values = c(pass = "solid", "scholarship eligible" = "dashed")
  ) +
  scale_color_manual(
    name = "Project Performance",
    values = c(pass = "red", "scholarship eligible" = "darkgreen")
  ) +
  # 强制移除图例中的点符号
  guides(
    linetype = guide_legend(override.aes = list(shape = NA)),
    color = guide_legend(override.aes = list(shape = NA))
  ) +
  new_scale_color() +
  geom_point(aes(colour = pass_sat),
             show.legend = TRUE) +
  scale_color_manual(name = "SAT Performance", values = c("Met Threshold" = "purple", "Did Not Meet Threshold" = "black")) +
  labs(title= "Total SAT by Overall Project Score, by Year")

关键说明:

  1. geom_point(show.legend = FALSE):阻止基础散点的图例元素生成,避免它的点符号混入“Project Performance”图例。
  2. guides()中的override.aes = list(shape = NA):强制让“Project Performance”图例只显示线型和颜色,不渲染任何点形状。

修改后,“Project Performance”图例就只会展示对应颜色的线型和标签,黑点会被完全移除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:20:28