Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ggplot2 legend not show in the graph [duplicate]

Tags:

r

legend

ggplot2

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

like image 952
Angli Xue Avatar asked Dec 05 '16 04:12

Angli Xue


People also ask

Why is there no legend ggplot?

The general cause for the legend to not appear is, that you are ignoring the syntax of ggplot(). You have to adjust your data frame to work with ggplot.

How do I add a legend in ggplot2?

Adding a legend If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.

What does %>% do in ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

What does GG stand for in ggplot?

ggplot2 [library(ggplot2)] ) is a plotting library for R developed by Hadley Wickham, based on Leland Wilkinson's landmark book The Grammar of Graphics ["gg" stands for Grammar of Graphics].


1 Answers

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

like image 135
9Heads Avatar answered Sep 30 '22 18:09

9Heads