Numbers in legend : control for order

Hi,

My issue is that I want to plot a distribution with sta_function, but with different parameters. On the legend I want to report the values, but since ggplot sorts the numbers in alphabetic order, 10 comes before 3. Do you know any solution for controlling the order in this situation?

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.6.3
ggplot(data.frame(x = c(0, 20))) +
     stat_function(fun = dchisq, args = list(df = 1), aes(x = x, color = "1"), size = 1.5) +
     stat_function(fun = dchisq, args = list(df = 3), aes(x = x, color = "3"), size = 1.5) +
     stat_function(fun = dchisq, args = list(df = 6), aes(x = x, color = "6"), size = 1.5) +
     stat_function(fun = dchisq, args = list(df = 10), aes(x = x, color = "10"), size = 1.5) +
     stat_function(fun = dchisq, args = list(df = 15), aes(x = x, color = "15"), size = 1.5) +
     stat_function(fun = dchisq, args = list(df = 99), aes(x = x, color = "99"), size = 1.5) +
  labs(
       y = "", x = ""
     )
#> Warning: `mapping` is not used by stat_function()
#> Warning: `mapping` is not used by stat_function()

#> Warning: `mapping` is not used by stat_function()

#> Warning: `mapping` is not used by stat_function()

#> Warning: `mapping` is not used by stat_function()

#> Warning: `mapping` is not used by stat_function()

Created on 2020-09-22 by the reprex package (v0.3.0)

Reprex enclosed,
Thank you for your help in advance
Marcell

the most trivial solution would be to pad a space for "1" "3" and "6" to make them " 1" " 3" " 6"
Alphabetic sorting will then work.

There's a nice little post here which has a section on how to change the order of items in the legend:


That said, because you're constructing the data inside the ggplot2 call, I'm not sure you'd be able to reference them together as a scale…so, if you want to keep it as is, I think @nirgrahamuk has given you your easiest option.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.