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

如何为含两个geom_point的ggplot绘图添加avg图例?

Got it, let's figure out how to add that blue triangle legend for your avg values!

The problem right now is that your blue triangle points are using hard-coded color and pch values outside of the aes() mapping—ggplot only automatically creates legends for aesthetics that are mapped inside aes(), not for fixed values you set directly.

Here's the adjusted code that adds the legend you want, with explanations:

library(ggplot2)
library(forcats)

dat = data.frame(group = rep("A",3),subgroup= c("B","C","D"), value= c(4,5,6),avg = c(4.5,4.5,4.5))

ggplot(dat, aes(x= group, y =value, color = fct_rev(subgroup) ))+ 
  geom_point()+ 
  # Move color and shape into aes() so ggplot recognizes it as a legend-worthy category
  geom_point(data = dat, aes(x = group, y = avg, color = "avg", shape = "avg"), inherit.aes = FALSE) +
  # Define custom colors: map "avg" to blue, and keep your subgroup colors
  scale_color_manual(
    values = c("avg" = "blue", "B" = "#F8766D", "C" = "#00BA38", "D" = "#619CFF")
  ) +
  # Define the triangle shape for "avg" and set the legend title to "avg"
  scale_shape_manual(
    name = "avg",
    values = c("avg" = 17)
  ) +
  # Optional: Clean up legends to combine them neatly
  guides(
    color = guide_legend(title = NULL), # Remove extra title for color legend
    shape = guide_legend(title = "avg")
  )

Key changes explained:

  • Move aesthetics to aes(): By setting color = "avg" and shape = "avg" inside aes() for the avg points, we tell ggplot to create legend entries for this category.
  • Manual scales: scale_color_manual and scale_shape_manual let us explicitly set the blue color and triangle shape for the "avg" entry, while matching the default colors for your subgroups (you can tweak those hex codes if you want different subgroup colors).
  • Guide adjustment: The guides() function helps merge the color and shape legends into a single clean one, with the title "avg" as you requested.

If you prefer separate legends, you can skip the guides() part—ggplot will show two legends, one for subgroup colors and one for the avg shape/color.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:47:07