How to reorder the items in a legend?

前端 未结 2 1482
暗喜
暗喜 2020-12-03 05:24

I\'m trying to change the order in which legend items appear. I\'ve spent about an hour at this, with no results.

Here\'s an example setup:

library(         


        
2条回答
  •  渐次进展
    2020-12-03 06:06

    The order of legend labels can be manipulated by reordering and changing values in column a to the factor: d$a <- factor(d$a, levels = d$a)

    So your code would look like this

    library(ggplot2)
    set.seed(0)
    d <- data.frame(x = runif(3), y = runif(3), a = c('1', '3', '10'))
    
    d$a <- factor(d$a, levels = d$a)
    
    ggplot(d, aes(x = x, y = y)) + 
      geom_point(size=7, aes(color = a))
    

    And the ouptut

    Note, than now in legend: 1 is red, 3 is green and 10 is blue color

提交回复
热议问题