Home > Blockchain >  Two legends ggplot
Two legends ggplot

Time:12-31

I am trying to create a line plot with ggplot by group, but I get two legends. I managed to edit the first legend to be as I want, but I cannot get rid of the second one. How can I keep only the legend I need?

My code is as follows:

ggplot(data=data_Frame, aes(x=year, y=percent, group=legal, colour=as.factor(legal)))  
  geom_line(aes(linetype=as.factor(legal))) 
  geom_point() 
  geom_label_repel(aes(label = scales::percent(round(percent, digits=2))), nudge_x = 0.35, size = 3) 
  labs(y= "% of total cases", 
         x = "Year",
         title="Evolution of legal activity")  
  theme_classic() 
  scale_color_discrete(name = "Legality",
                        labels = c("Legal", "Not legal"))

and my dataset is as follows:

structure(list(year = c(2013, 2014, 2014, 2015, 2015, 2016, 2016, 
2017, 2017, 2018, 2018, 2019, 2019, 2020, 2020, 2021, 2021, 2022, 
2022), legal = c(0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 
0, 1, 0, 1), local = c("yes", "yes", "yes", "yes", "yes", "yes", 
"yes", "yes", "yes", "yes", "yes", "yes", "yes", "yes", "yes", 
"yes", "yes", "yes", "yes"), percent = c(0.0833116184157648, 
0.134483022523174, 0.231061069599069, 0.0560278636136179, 0.272460808191276, 
0.10522051542274, 0.0823949547509575, 0.0902594024920258, 0.173996656575591, 
0.171213948427101, 0.331143680934122, 0.136188084988968, 0.219662510799276, 
0.0968133762744133, 0.216020359140314, 0.0929078672288155, 0.181961094549172, 
0.0871273239449852, 0.0913038796855186)), row.names = c(NA, -19L
), class = "data.frame")

CodePudding user response:

You can simply add show.legend = FALSE in your geom_line:

ggplot(data = data_Frame, aes(x=year, y=percent, group=legal, colour=as.factor(legal)))  
  geom_line(aes(linetype = as.factor(legal)), show.legend = FALSE)  
  geom_point() 
  ggrepel::geom_label_repel(aes(label = scales::percent(round(percent, digits=2))), nudge_x = 0.35, size = 3) 
  labs(y= "% of total cases", 
       x = "Year",
       title="Evolution of legal activity")  
  theme_classic() 
  scale_color_discrete(name = "Legality",
                       labels = c("Legal", "Not legal"))

enter image description here

CodePudding user response:

Add guides(linetype = "none") to remove the legend associated with linetype=.

ggplot(data=data_Frame, aes(x=year, y=percent, group=legal, colour=as.factor(legal)))  
  geom_line(aes(linetype=as.factor(legal))) 
  geom_point() 
  ggrepel::geom_label_repel(aes(label = scales::percent(round(percent, digits=2))), nudge_x = 0.35, size = 3) 
  labs(y= "% of total cases", 
         x = "Year",
         title="Evolution of legal activity")  
  theme_classic() 
  scale_color_discrete(name = "Legality",
                       labels = c("Legal", "Not legal"))  
  guides(linetype = "none")

enter image description here

  • Related