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

ggplot2添加图例问题求助:已尝试常规操作仍未成功

Fixing Legend Display for SMA Lines in tidyquant + ggplot2

Hey Ann, I’ve run into this exact issue before! The problem is that when you set col directly inside geom_ma(), you’re hardcoding the color instead of mapping it to an aesthetic that ggplot can use to generate a legend. Here’s how to fix it:

Step-by-Step Fix

  • Move the color assignment into the aes() call for each geom_ma(), and give each SMA a descriptive label (this will be what shows up in the legend)
  • Add scale_color_manual() to explicitly map those labels to your desired colors

Modified Code

data %>% 
  ggplot(aes(date, price)) + 
  geom_line() + 
  geom_ma(ma_fun = SMA, n = 50, size = 1, aes(color = "50-Day SMA")) + 
  geom_ma(ma_fun = SMA, n = 200, size = 1, aes(color = "200-Day SMA")) + 
  scale_color_manual(values = c("50-Day SMA" = "red", "200-Day SMA" = "blue")) +
  theme_tq()

Why This Works

When you use aes(color = "Label"), you’re telling ggplot that this line belongs to a category with that label. The scale_color_manual() then links those labels to the specific colors you want, and ggplot automatically generates a legend based on that mapping. Your original code used col = "red" which skips the aesthetic mapping step—great for setting color, but not for creating legends!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:12:44