0

Here is my code for a ggplot with multiple lines, however I wanted to add a legend which labelled the black line as "Close price" and the Blue as "RSI"


pRSI<-getSymbols("AAPL",src = "yahoo", from="2010-01-01",to="2014-02-01",auto.assign=F)
    df<-as.data.frame(pRSI)
    df<-df[complete.cases(df),]
    n<-nrow(df)
    df$RSI<-RSI(df[,4],n=14,wts=df[,6])
    ggplot()+
        geom_line(data=df,aes(y=RSI,x=c(1:n)),color="blue")+
        geom_line(data=df,aes(y=df[,4],x=c(1:n)),color="black")+
        xlab('Data Point')+
        ylab('Price')

  • 1
    Hi George, thanks for your question but could you please provide a full mimimum reproducible example so I (and others) can help? Thanks. – Simon Mar 02 '20 at 11:03
  • 1
    This question seems to be a duplicate, see following link for possible solutions https://stackoverflow.com/questions/18394391/r-custom-legend-for-multiple-layer-ggplot – M_Shimal Mar 02 '20 at 11:10
  • @M_Shimal `scale_colour_manual(name = 'Key',guide='legend', values =c('blue'='blue','black'='black'), labels = c('Close Price','RSI'))` I have tried adding such code using thread above with no joy – George Loftus Mar 02 '20 at 11:28
  • @GeorgeLoftus the point is that you need to set the colour within the geometry aesthetic for ggplot to realise that a legend is needed. – George Savva Mar 02 '20 at 13:06

1 Answers1

0

As George Savva mentioned in comments, ggplot puts in legend when colour goes inside the aesthetics.

You can get the legends using the code below.

pRSI<-getSymbols("AAPL",src = "yahoo", from="2010-01-01",to="2014-02-01",auto.assign=F)

df<-as.data.frame(pRSI)

df<-df[complete.cases(df),]
n<-nrow(df)
df$RSI<-RSI(df[,4],n=14,wts=df[,6])

df <- data.frame(RSI = rep(c("a","b","c"), 10),  = sample(c(1:50), 30))

ggplot()+
  geom_line(data=df,aes(y=RSI,x=c(1:n), color='blue - series'))+
  geom_line(data=df,aes(y=df[,4],x=c(1:n), color='black - series')) +
  scale_color_manual(name = "legend name", values = c("blue","black")) + 
  xlab('Data Point')+
  ylab('Price')

enter image description here

M_Shimal
  • 413
  • 3
  • 12