Pr1
Pr1

Reputation: 51

How do I keep the original order in ggplot2

I have the following code:

df <- data.frame(Days = days,Temperature = temp)
pl <- ggplot(df,aes(x=Days,y=Temperature)) + geom_point()
print(pl)

When I try running this code it shows the days in alphabetical order instead of the index order (Mon,Tue,Wed,Thu,Fri). How can I change it to the correct order?

Upvotes: 2

Views: 2446

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226097

After a little bit of searching I found a built-in English-weekday-abbreviation object (in correct order) by installing the DescTools package. Using

data.frame(Days=factor(days,levels=DescTools::day.abb), ...)

seems to be the most principled way to do this (I can't think of an easy way to do this with weekday name abbreviations from another locale ...)

Upvotes: 3

Justin In Oz
Justin In Oz

Reputation: 310

The below code works:

library(ggplot2)

days <- c("Mon","Tue","Wed","Thu","Fri")
temp <- c(21, 24, 34, 23, 23)

df2 <- data.frame(Days2=factor(days,levels=unique(days)), Temperature2 = temp)

pl2 <- ggplot(df2,aes(x=Days2,y=Temperature2)) + geom_point()
print(pl2)

It produces the below graph: enter image description here

Upvotes: 4

Related Questions