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 eachgeom_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
相关产品推荐
相关产品推荐

