7

I use ggplot to scatterplot 2 datasets and want to show the legend in the top left. I tried some code but didn't work. I am not sure why this happened.

ggplot(mf, aes(log10(mf[,2]),mf[,1])) 
+ ggtitle("Plot") 
+ geom_point(color = "blue") +  theme(plot.margin = unit(c(1,2,1,1), "cm"))
+ xlab("xxx") + ylab("yyy") 
+ theme(plot.title = element_text(size=18,hjust = 0.5, vjust=4)) 
+ geom_point(data=mf2,aes(log10(mf2[,2]),mf2[,1]),color="red") 
+ theme(axis.title.x = element_text(size = rel(1.3))) 
+ theme(axis.title.y = element_text(size = rel(1.3))) 
+ scale_color_discrete(name = "Dataset",labels = c("Dataset 1", "Dataset 2"))

enter image description here

MBorg
  • 1,345
  • 2
  • 19
  • 38
Angli Xue
  • 81
  • 1
  • 1
  • 6

1 Answers1

12

Since values were not provided, I have used my own values for the demonstration purpose.

mf is a dataframe with log and val as it's column.

You need to put the color parameter inside the aesthetics. This will result in the mapping of colors for the legend. After that you can manually scale the color to get any color you desire.

you can use the below code to get the desired result.

ggplot(mf, aes(val,log))+
    geom_point(aes(color = "Dataset1"))+
    geom_point(data=mf2,aes(color="Dataset2"))+
    labs(colour="Datasets",x="xxx",y="yyy")+
    theme(legend.position = c(0, 1),legend.justification = c(0, 1))+
    scale_color_manual(values = c("blue","red"))

The Output

9Heads
  • 688
  • 3
  • 7
  • 1
    I've another method that merges two datasets together using "reshape2" and "melt". But your method is much more elegant! – Angli Xue Dec 06 '16 at 04:33