Estelle Duval Estelle Duval - 22 days ago 4
R Question

ggplot2 legend does not take place in graph?

Here my code :

modele <- ggplot(data = liste_ref, aes(x = BV, y = liste_ref[,p]))+
geom_point(aes(text = paste("Code opération: ",OPE_ID), colour = "FRANCE"),size = 1)+
geom_point(data = liste_ref_HER,aes(y = liste_ref_HER[,p],text = paste("Code operation: ",OPE_ID),colour = "HER"),size=1)+
geom_point(data = select,aes(y = select[,p],text = paste("Code operation: ",OPE_ID), colour = "Selection"),size=1)+
scale_y_log10() + scale_x_log10()+
stat_smooth(aes(x = BV, y = liste_ref[,p]), method = "lm",formula = y ~ x, se = FALSE,size = 0.25,fullrange = TRUE,color = "#BABBBF")+
stat_smooth(data = liste_ref_HER, aes(x = BV, y = liste_ref_HER[,p]), method = "lm",formula = y ~ x, se = FALSE,size = 0.25,fullrange = TRUE, color = "#2F61F5")+
scale_color_manual(name = "Legend", values = c("FRANCE"="#BABBBF","HER"="#2F61F5","Selection"="red"))+
ggtitle(paste("Relation entre la surface du bassin versant et ",pl," de l'HER",HER[,1]))+
xlab("Surface du bassin versant (en km²)") + ylab(yl)

ggplotly(modele)


And it result :
enter image description here

The legend doesn't have enought space to appear... Please help me !

Answer

Here is an alternative. Would this work for you?

#create a new dataset with a new column with 3 factor levels:
liste_ref$Test <- "liste_ref"
liste_ref_HER$Test <- "liste_ref_HER"
select$Test <- "select"
FinalData <- rbind(liste_ref, liste_ref_HER, select)


ggplot(data = FinalData, aes(x = BV, y = Moy_Lm_Qb, color=Test))+
geom_point(size = 1) + scale_y_log10() + scale_x_log10() + 
stat_smooth(data = FinalData, aes(x = BV, y = Moy_Lm_Qb, color=Test), method = "lm",formula = y ~ x, se = FALSE,size = 0.25,fullrange = TRUE) + 
scale_color_manual(name = "Legend", values = c("liste_ref"="#BABBBF","liste_ref_HER"="#2F61F5","select"="red")) +
ggtitle("Relation entre la surface du bassin versant et l'HER")

#adjust margin
m = list( l = 100, r = 100, b = 50, t = 50, pad = 0)
ggplotly() %>% layout(autosize = F, width = 1200, height = 600, margin = m)

enter image description here

Comments