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

自定义主题下ggplot多折线图添加右侧图例失败问题求助

问题根源

你的代码无法生成图例是因为colour参数写在了aes()外部,属于固定图层属性,ggplot不会为固定属性生成图例,只有映射到aes()内的变量才会触发图例渲染。你额外添加的aes()外层括号属于语法错误,需先移除。

可行解决方案(保留多次调用geom_line的写法)

修改思路:将每个线条的colour映射到aes()内的自定义标签,再通过scale_colour_manual绑定指定颜色即可。

完整代码

# 自定义主题(保持你原有配置不变)
CustomTheme <- theme(
  legend.text = element_text(face = "bold", colour = "black", family = "Helvetica"),
  axis.title = element_text(colour = "blue", family = "Helvetica"),
  axis.line = element_line(size = 0.8, colour = "grey"),
  axis.ticks = element_line(colour = "grey"),
  panel.grid.major = element_line(colour = "grey"),
  panel.grid.minor = element_blank(),
  panel.background = element_rect(fill = "white"),
  legend.title = element_text(colour = "black", face = "bold", family = "Helvetica"),
  legend.position = "right",
  plot.title = element_text(colour = "blue", face = "bold", family = "Helvetica", size = 9, hjust = 0.5)
) 

# 修改后的绘图代码
line1 <- ggplot() + 
  geom_line(data = subsetGED, aes(x = year , y = primary_energy_consumption, colour = "一次能源消费量"), na.rm = TRUE, size = 1) + 
  geom_line(data = subsetGED, aes(x = year , y = renewables_share_electricity, colour = "可再生能源电力占比"), na.rm = TRUE, size = 1) + 
  geom_line(data = subsetGED, aes(x = year , y = renewables_share_energy, colour = "可再生能源总占比"), na.rm = TRUE, size = 1) + 
  xlab("Year") + 
  ylab("Energy Consumption (TWh)") + 
  xlim(1960, 2019) + 
  ggtitle("How renewable energy contributes to total energy consumption, illustrated with global electricity usage" ) + 
  scale_y_continuous(trans='log10') + 
  # 手动绑定颜色和标签,同时设置图例标题
  scale_colour_manual(
    name = "指标名称",
    values = c("一次能源消费量" = "blue", "可再生能源电力占比" = "yellow", "可再生能源总占比" = "green")
  ) +
  CustomTheme

print(line1)

运行后会自动在图表右侧生成图例,和你自定义主题的legend.position = "right"配置完全匹配,不需要额外调整位置参数,aes()内的标签名称可根据你的需求自定义修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:06:04