Home > Enterprise >  Legend issue with ggplot graphic in R
Legend issue with ggplot graphic in R

Time:10-04

enter image description heregreetings!

Please I've plotted an empirical cumulative distribution with using ggplot and geom_line commands in R. The variable plotted are the yields of three sorghum varieties "soubatimi", "tiandougou-coura" and "local" with the respective colour:green, blue and red.But I am not able to add legend to the chart with the respective colour set. here is the dput(abc)

dput(abc)
structure(list(year = c(2018L, 2017L, 2020L), y_soubatimi = c(1614L, 
1665L, 2181L), prob_soub = c(0.047619048, 0.083333333, 0.041666667
), cum_prob_s = c(0.047619048, 0.130952381, 0.172619048), year.1 = c(2018L, 
2020L, 2017L), y_tiandougou_coura = c(1440L, 1475L, 1635L), prob_tc = c(0.047619048, 
0.041666667, 0.083333333), cum_prob_tc = c(0.047619048, 0.089285714, 
0.172619048), year.2 = c(2020L, 2018L, 2017L), y_local = c(916L, 
945L, 1080L), prob_loc = c(0.041666667, 0.047619048, 0.083333333
), cum_prob_loc = c(0.041666667, 0.089285714, 0.172619048)), class = "data.frame", row.names = c(NA, 
-3L))
   ggplot() geom_line(data=abc,aes(x=y_soubatimi),(stat="ecdf"),col="green") 
   geom_line(data=abc,aes(x=y_tiandougou_coura),(stat="ecdf"),col="blue") 
   geom_line(data=abc,aes(x=y_local),(stat="ecdf"),col="red") 
   labs(x= "Yields,kg/ha",y = "Probability") 
   scale_colour_discrete(name  = "", 
                      breaks= c("souba", "tiand", "loca"),
                      labels= c("y_soubatimi", "y_tiandougou_coura", "y_local"))  
   theme_bw()  
   theme(panel.grid.major.y = element_blank(), 
         axis.text.x = element_text(size=10), 
         axis.text.y = element_text(size=10), 
         legend.text =element_text(size=10))

CodePudding user response:

Instead of adding three geom_line()s and manually specifying the colour in each, try adding one geom_line() and setting the colour in the aes() based on values in a column. Since it looks your data is in 3 separate columns you'll likely need a call to pivot_longer().

Here's an example that does what I think you're looking for using the data you provided:

library(tidyverse)

abc %>%
  pivot_longer(cols = c(y_soubatimi, y_tiandougou_coura, y_local)) %>%
  ggplot()  
  geom_line(aes(x=value, colour = name),
            stat = "ecdf")  
  labs(x= "Yields,kg/ha",y = "Probability") 

And the result: a ggplot ecdf

It now has the legend matching species with colour. Let me know if you're looking for something else.

  • Related