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

在RStudio中使用ggplot移除图例框中的黑色点

解决ggplot2双Y轴图表图例多余黑点问题

问题根源

你的代码重复添加了温度相关的geom_point和geom_line图层,其中两个图层在aes内设置了color = "temperature",这会让ggplot自动为该系列生成图例项;再加上之前无映射的geom_point,最终导致图例出现多余黑点。

修正后的代码

library(tidyverse)
library(ggplot2)

values <- c("v","c")
G1 <- c(1,5,1,4,0,5,0,5,1,2,0,7,5,5,1,2,1,1,5,6,2,4,0,3,0,3,3,17)
G2 <- c("A","A","B","B","C","C","D","D","E", "E", "F", "F", "G","G", "H","H","I", "I","J", "J", "K","K", "L", "L","M", "M", "N", "N")
temperature <- c(-0.81,-0.81,-0.91, -0.91,-1.01, -1.01,-0.99, -0.99,-0.92,
                -0.92,-0.82,-0.82, -0.67,-0.67,-0.43, -0.43, -0.14,-0.14,
                 0.16,0.16, 0.48, 0.48, 0.77,0.77, 1.07, 1.07, 1.32,1.32)
data1 <- data.frame(x = G2, y= G1, values) 

ylim.prim <- c(0, 20)
ylim.sec <- c(-1.5,1.5)

b <- diff(ylim.prim)/diff(ylim.sec) 
a <- (ylim.prim[1] - b*ylim.sec[1]) 

ggplot(data1, mapping = aes(x = x, y=G1, fill = values))+
  geom_bar(stat = "identity", color = "black") + 
  scale_fill_manual(name = "", values = c("purple", "green"),
                    labels = c("EMPTY", "FULL")) +
  # 保留温度线和点,直接设置颜色并关闭图例显示
  geom_line(aes(y = a + temperature*b), group=1, color = "#483D8B", lwd=1, show.legend = FALSE)+
  geom_point(aes(y = a + temperature*b), color = "black", show.legend = FALSE)+  
  theme_classic()+  
  theme(axis.title.y = element_text(size = 10, color = "black", face = "italic"))+ 
  theme(axis.text.x = element_text(color = "black", size = 7, angle=90), 
        axis.text.y = element_text(color = "black", size = 8, hjust = 1))+
  theme(axis.title.x = element_blank()) +
  scale_y_continuous(sec.axis = sec_axis(~(. - a)/b, 
                                         breaks = c(-1.3,-1.1,-0.9,-0.5,0, 0.5,0.9,1.1,1.3), 
                                         name = "temperature")) +
  theme(legend.background = element_rect(fill = "transparent"),
        legend.box.background = element_rect(fill = "transparent", colour = NA),
        legend.key = element_rect(fill = "transparent"),
        legend.spacing = unit(-1, "lines"))+
  expand_limits(y = c(0,0))+
  labs(title="", x=NULL, y="G")

关键修改说明

  • 移除了重复的、带color = "temperature"映射的geom_line和geom_point图层,这些是生成多余图例项的核心原因。
  • 保留温度相关的线和点图层,直接在图层外设置color参数(而非aes内),并添加show.legend = FALSE,确保它们不会出现在图例中。
  • 修正了labs中的x参数,避免将G2向量错误设置为轴标题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:46:23