1

I hope to make custom legend for my graph, and I referenced this two posts posts posts

I tried it, but it doesn't work

g2=ggplot(data=juga, aes(x=Date, group=0))+
geom_line(aes(y=Dow),colour="cornflowerblue")+
geom_line(aes(y=NASDAQ),colour="firebrick2")+
geom_line(aes(y=S.P.500),colour="gold2")+
geom_line(aes(y=Nikkei.225),colour="gray69")+
geom_line(aes(y=Shanghai),colour="forestgreen")+
geom_line(aes(y=KOSPI),colour="black")+
xlab("Dates") +ylab("Values")+
ggtitle("Juga graph") 
g2

This is my original codes and its graph looks like thisenter image description here

To add legend, I changed codes like this

cols <- c("A"="cornflowerblue","B"="firebrick2","C"="gold2", "D"="gray69", "E"="forestgreen", "F"="black")
g2=ggplot(data=juga, aes(x=Date, group=0))+
geom_line(aes(y=Dow),colour="A")+
geom_line(aes(y=NASDAQ),colour="B")+
geom_line(aes(y=S.P.500),colour="C")+
geom_line(aes(y=Nikkei.225),colour="D")+
geom_line(aes(y=Shanghai),colour="E")+
geom_line(aes(y=KOSPI),colour="F")+
scale_colour_manual(values=cols)+xlab("Dates") +ylab("Values")+
ggtitle("Juga graph")
g2

But this code makes erros

Error in grDevices::col2rgb(colour, TRUE) : invalid color name 'A'

How can I fix them?

JRB
  • 1,943
  • 1
  • 10
  • 9
user4315272
  • 143
  • 1
  • 2
  • 13
  • First, I suggest you provide a reproducible example - like in the posts that you referenced. – lukeA Dec 03 '15 at 11:42
  • 1
    Maybe easier would be to `melt` the data, then use `group` based on your groups (variable) and set `color` inside `aes` to your variable. Then you can specify color manually and avoid putting 5 more `geom_line`. – Volodymyr Dec 03 '15 at 12:34

1 Answers1

0

Try this:

library(reshape2)

df <- melt(juga,id.vars="Date")
cols <- c("Dow"="cornflowerblue","NASDAQ"="firebrick2","S.P.500"="gold2",
          "Nikkei.225"="gray69","Shanghai"="forestgreen","KOSPI"="black")

g2 <- ggplot(df,aes(x=Date,y=value,group=variable,color=variable))+
  geom_line()+xlab("Dates")+ylab("Values")+ggtitle("Juga graph")+theme_bw()
  scale_colour_manual(values=cols)

Also, if your dates are not already in a date format, I would recommend converting them so that the dates are visible on the x-axis. I can't really see what format they're in currently, but you might be able to do something like:

df$Date <- as.Date(df$Date)
Sam Dickson
  • 5,082
  • 1
  • 27
  • 45