Home > Software engineering >  My ggplot includes geom_boxplot and geom_line, but it does not show the legend for the geom_line par
My ggplot includes geom_boxplot and geom_line, but it does not show the legend for the geom_line par

Time:09-08

My ggplot includes geom_boxplot and geom_line, but it only shows the legend for the boxplot part but does not show the legend for the geom_line part. How can I add it please?

Note: The boxplot and the line were made from two different data sources, but shown in one graph.

I really need help with this please, thank you!

Here is the code:

library(ggnewscale)

    bplot6 <- ggplot(seasonalmerge_neale1989)  
  geom_boxplot(aes(x = date, y = values, group = date, fill = `Data Source`), width = 2, outlier.shape = NA,
               lwd = 0.1)  
  xlab("")  
  ylab("")  
  ylim(0,1.2)  
  theme(
    axis.text.x = element_text(family="serif", size = 8),
    axis.text.y = element_text(family="serif", size = 8),
    legend.title = element_text(family="serif", size = 8),
    legend.text = element_text(family="serif", size = 8),
    plot.title = element_text(family="serif", face="bold", size = 8, hjust = 0.5))  
  ggtitle("(f)") 
  new_scale_color()  
  geom_line(data=pointframe, aes(x= pointdate, y=pointvar), colour="gold", size=1, method = "lm", se=FALSE)
#  theme_classic() scale_linetype_manual(values=bplot6, name="Data Source: ", labels=c("Ceres", "Landsat", "FAO"))  theme(legend.position = "bottom")

bplot6

image of boxplots and line

CodePudding user response:

A color must be specified inside an aesthetic in order for there to be a legend. Moving colour inside aes() will build a legend automatically. Then we can adjust the labels and colors with scale_color_manual. Reproducing your code using iris data.

library(ggnewscale)
bplot6 <- ggplot(iris)  
geom_boxplot(aes(x = Petal.Length, y = Petal.Width , group = Species, fill = `Species`), width = 2, outlier.shape = NA,lwd = 0.1)  
xlab("")  
ylab("")  
#ylim(0,1.2)   you can use it as per your requirement
theme(
axis.text.x = element_text(family="serif", size = 8),
axis.text.y = element_text(family="serif", size = 8),
legend.title = element_text(family="serif", size = 8),
legend.text = element_text(family="serif", size = 8),
plot.title = element_text(family="serif", face="bold", size = 8, hjust = 0.5))  
ggtitle("(f)") 
new_scale_color()  
geom_line(data=iris,  aes(x= Sepal.Length, y=Sepal.Width, color="Gold"), size=1) 
scale_color_manual(name = "Colour", values = c("Gold" = "gold"))
#  theme_classic() scale_linetype_manual(values=bplot6, name="Data Source: ", labels=c("Ceres", "Landsat", "FAO"))  theme(legend.position = "bottom")

bplot6
  • Related