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

R ggplot2中show.legend = FALSE不生效问题(附代码数据)

ggplot中show.legend = FALSE未生效的原因解析

问题根源

你代码里的图例并非来自geom_text,而是由geom_bar生成的:

  • 你在ggplot()的全局美学映射(aes)中设置了fill = CITYNAME,这个映射会被geom_bar继承,因此geom_bar基于填充色的分组逻辑生成了图例。
  • 你把show.legend = FALSE加在了geom_text的参数里,但geom_text并没有使用fill这个美学属性(它的aes仅定义了label),所以这个设置对geom_bar生成的图例完全没有影响。

两种解决方法

方法1:直接在geom_bar中关闭图例

将show.legend = FALSE移到geom_bar的参数中,因为图例是它生成的:

# Plot in Fahrenheit
df %>% mutate(AvgTMin = AvgTMin * (1.8) + 32) %>% # 摄氏度转华氏度
      ggplot(aes(x = reorder(CITYNAME,AvgTMin), y = AvgTMin, fill = CITYNAME)) +
      geom_bar(stat="identity", show.legend = FALSE) + # 在此处设置关闭图例
      coord_cartesian(ylim = c(60,70.3)) +
      theme(axis.text = element_text(size = 14)) +
      geom_text(aes(label=sprintf("%0.2f", AvgTMin)), vjust=-0.2, size = 4) +
      labs(x = NULL, y = "Avg. Min. Temperature °F") + 
      theme(axis.text.x = element_text(angle = 90)) +
      ggtitle("1980-2021 Temperature Trend By City")

方法2:将填充色映射移到geom_bar的局部美学中

把fill = CITYNAME从全局aes里挪到geom_bar的局部aes中,这样只有geom_bar使用这个映射,不会生成全局图例:

# Plot in Fahrenheit
df %>% mutate(AvgTMin = AvgTMin * (1.8) + 32) %>% # 摄氏度转华氏度
      ggplot(aes(x = reorder(CITYNAME,AvgTMin), y = AvgTMin)) + # 全局aes移除fill设置
      geom_bar(aes(fill = CITYNAME), stat="identity") + # 局部设置fill映射
      coord_cartesian(ylim = c(60,70.3)) +
      theme(axis.text = element_text(size = 14)) +
      geom_text(aes(label=sprintf("%0.2f", AvgTMin)), vjust=-0.2, size = 4) +
      labs(x = NULL, y = "Avg. Min. Temperature °F") + 
      theme(axis.text.x = element_text(angle = 90)) +
      ggtitle("1980-2021 Temperature Trend By City")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:25:25