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

在R语言ggplot2中移除图例中的标准差误差线与均值标记,保留图表主体对应元素

Fix: Keep Mean & SD Error Bars on Plot, Remove Them from Legend

Got it! The issue here is that your stat_summary layer is adding entries for the mean point and error bars to your legend, even though you only want those elements visible on the plot itself. Here are two simple, targeted fixes:

Method 1: Hide Legend Entries Directly in stat_summary

The easiest way is to add the show.legend = FALSE parameter to your stat_summary call. This tells ggplot to render the mean and error bars on the plot, but exclude them from the legend entirely.

Modified Code Snippet (Key Line Changed)

stat_summary(fun.data=data_summary, color="black", position=position_dodge(width=0.75), size = 1.3, show.legend = FALSE)

Full Modified Code

data_summary <- function(x) { 
  m <- mean(x) 
  ymin <- m-std.error(x) 
  ymax <- m+std.error(x) 
  return(c(y=m,ymin=ymin,ymax=ymax)) 
}

a <- ggplot(esto, aes(x= Group, y=value, colour = Group, fill=fluency_test)) + 
  geom_boxplot(outlier.shape = NA, lwd=1.5) + 
  guides(colour = "none") + 
  geom_point(position=position_jitterdodge(), alpha=0.5) + 
  xlab("Group") + 
  labs(y = names(features)[[i_feature]]) + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) + 
  stat_summary(fun.data=data_summary, color="black", position=position_dodge(width=0.75), size = 1.3, show.legend = FALSE) + 
  scale_shape_manual("Summary Statistics", values=c("Mean"="+")) + 
  scale_color_manual(values=c("#7CAE00","#F8766D","#00BFC4","#C77CFF")) + 
  scale_fill_manual(values=c("white","azure3")) + 
  theme_gray(base_size = 18) + 
  theme(legend.key.size = unit(2, "cm"), 
        legend.key.width = unit(1,"cm"),
        legend.title=element_blank(),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(), 
        panel.background = element_blank(), 
        axis.line = element_line(colour = "black"))

Method 2: Override Legend via guides() (If Needed)

If you need more control over specific legend elements (e.g., only remove the mean shape entry), you can use guides() to turn off the shape legend (since your mean is mapped to a shape with scale_shape_manual):

guides(shape = "none")

Add this line to your plot code (after the scales) to remove the "Mean" entry from the legend. Note this will hide all shape-based legend entries, so use this only if you don't have other shape mappings you want to keep visible.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:49:09