Home > Mobile >  Duplicated legends in ggplot2 for colour and point shape
Duplicated legends in ggplot2 for colour and point shape

Time:09-28

I have been fighting with this graph all day, comparing to other plots I have in which the issue does not occur and look at a good few links but there has been no success.

My graph has two legends. I would like to merge them. The outcome I want is for the legend to show as "Sample", "Analyser", "Grab" with a small black circle for analyser and a larger red triangle for grab.

enter image description here

CodePudding user response:

Here is another option. Remove the legend from the current points, add a blank point layer of size=0 to add a legend, use guides to format the legend how you want. I also cleaned up your plot code a bit. I like to keep all my geom_*, scale_*, labs, and theme lines together so that you don't override something later. I notices a few redundant lines.

library(tidyverse)


ggplot(data, aes(x = run, y = no2c, color = sample))   
  geom_point(aes(shape = sample, size = sample), show.legend = FALSE)   #remove from Legend
  geom_point(size = 0)  #add blank to format legend
  geom_line(aes(y=no2c), color="black", data = subset(data, sample == 'F'))  
  scale_size_manual(values = c(F = 2, G = 4))  
  scale_color_manual(name="Sample", 
                     labels=c("Analyser", "Grab"),
                     values = c("F"="black", "G"="red3")) 
  scale_x_continuous(breaks=seq(65,70,1),limits = c(65,70))  
  scale_y_continuous(breaks=seq(0,0.6,0.1), limits = c(0,0.6))  
  labs(title = expression(paste("C")),
       x = "Run number",
       y= expression(paste("NO"[2], " (mg " ~L^-1*'', ")")))   
  theme_bw()   
  theme(text = element_text(size=12),
        panel.border = element_rect(colour = "black", fill=NA, size=0.5),
        legend.position = "bottom", 
        legend.title=element_text(size=12), 
        legend.text = element_text(size=12),
        axis.title.y = element_text(size=12),
        plot.title = element_text(size=14, face="bold"),
        panel.grid.minor = element_blank(), 
        axis.line = element_line(colour = "black"),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))  
  guides(color = guide_legend(override.aes = list(size = c(2,4), shape = c("circle", "triangle"))))

  • Related