0

How can I change the order of legend elements to the numerical values instead of the alphabetical in ggplot? So i want to go from 1,10,2,3 to 1,2,3,10.

I know that i can set the order by hand for each graph separetely but I want to do automatically.

df <- data.frame(
  group=c("1_text","1_text","1_text","2_text","2_text","2_text", "10_text",
           "10_text","10_text"," 3_text","3_text","3_text"),
                 x=c(1,2,3,1,2,3,1,2,3,1,2,3),
                 y=c(1,2,3,4,5,6,7,8,9,10,11,12) )

ggplot(df,aes(x=x))+ 
  geom_line(aes(y=y,color=group)

I assume that I need to safe the group column as.factor(df$group) and then sort it by levels. With something like that:

sorted_group <- paste(sort(as.numeric(levels(df$group))))

However because my df$group elements aren't numerical it doesn't work. Is there a way to maybe do it directly in ggplot without doing changes on the dataframe itself?

Thank you for your help!

  • You can use the answer posted but to extract the numeric part of the string you can do something like: df <- data.frame( group1 = c( "1_text", "1_text", "1_text", "2_text", "2_text", "2_text", "10_text", "10_text", "10_text", "3_text", "3_text", "3_text" ), x = c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3), y = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) ) %>% mutate(grp_num = parse_number(as.character(group1))) %>% arrange(grp_num) %>% mutate(group1 = factor(group1, levels = unique(group1))) – Pete900 May 26 '22 at 09:41
  • FYI parse_number comes from the readr package – Pete900 May 26 '22 at 09:42
  • thank you for your answer, I have already tried a similar approach by splitting the "group elements" in two parts with the separate function and simply writing it to a new column. However, this way it just plots the numbers as legend elements without keeping the "text" that comes after the numbers. – Manfred Manfredo May 26 '22 at 09:54
  • I have tried around with your code and understood how your approach is different. Thank you very much! – Manfred Manfredo May 26 '22 at 10:43

0 Answers0