Search code examples
rggplot2r-factor

Sorting ggplot legends by factor (here: months)


If you consider this code:

library(ggplot2)
df <- as.data.frame(matrix(rnorm(8),4,2)) 
colnames(df) <- c("x","y") 
df$dates <- as.factor(c("april", "may", "june", "august"))

ggplot(df, aes(x=x, y=y, color=dates)) + geom_point(size=3, shape=20)

How can I sort the legend by the temporal sequence of the months?


Solution

  • Replace the df$dates<- line with:

    m <- c("april", "may", "june", "august")
    df$dates <- factor(m, levels = m)