简体   繁体   English

在ggplot2中添加图例

[英]Adding legend in ggplot2

I have looked through similar questions and I have a feeling I have done everything. 我已经看过类似的问题,并且觉得自己已经做了所有事情。 Still not getting the desire output. 仍然没有得到欲望的输出。 I am using ggplot2 and tidyquant packages to visualize data with 2 financial trends I am trying to display a legend that contains trends line coloron plot 我正在使用ggplot2tidyquant软件包来可视化具有2个财务趋势的数据,我试图显示一个包含趋势线颜色图的图例

data %>%
  ggplot(aes(date, price)) +
  geom_line() +
  geom_ma(ma_fun = SMA, n = 50, size = 1 , col = "red" , show.legend = TRUE)+
  geom_ma(ma_fun = SMA, n = 200, size = 1 , col = "blue", show.legend= TRUE)+
  theme_tq() 

在此处输入图片说明

Here you go: 干得好:

library(tidyquant)
library(ggplot2)
data <- data.frame(date = 1:1000, price = cumsum(rnorm(1000)))
data %>%
  ggplot(aes(date, price)) +
  geom_line() +
  geom_ma(aes(color = 'MA50'),  ma_fun = SMA, n = 50, size = 1 ,show.legend = TRUE)+
  geom_ma(aes(color =  'MA200'), ma_fun = SMA, n = 200, size = 1 , show.legend = TRUE) +
  scale_colour_manual(name = 'Legend', 
                      guide = 'legend',
                      values = c('MA50' = 'red',
                                 'MA200' = 'blue'), 
                      labels = c('SMA(50)',
                                 'SMA(200)'))

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM