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!