Eva Gunawan
Eva Gunawan

Reputation: 23

Order of dates is not chronological in ggplot2

I'm trying to make a graph to depict a population over a period of time. However, the dates are not in chronological order. In the imported CSV the dates are all correct and in order. However, once the code below is run, the graph presented does not have the dates in the correct order. The starting date is in the middle and the ending date is on the left of the starting date. Is there any way I can fix it?

sumc <- aggregate(ex2$C, bu=list(ex2$Date, ex2$Temp), FUN=sum)
colnames(sumc) <- c("Date", "Temperature", "Individuals")
ggplot(data= sumc, aes(x=Date, y=Individuals, group=Temperature, colour=Temperature )) + geom_line() + theme(plot.title = element_text(face="bold") 
    ,plot.background = element_blank()
    ,panel.background = element_blank()
    ,panel.grid.major = element_blank()
    ,panel.grid.minor = element_blank()
    ,panel.border = element_blank()
    ,axis.line = element_line(colour="black", size=1)
    ,axis.text.x = element_text(colour="black", size=10)
    ,axis.text.y = element_text(color="black", size=8)
    ,axis.title.x = element_text(colour="black", size=10, face="bold", vjust=-.2)
    ,axis.title.y = element_text(color="black", size=10, face="bold", vjust=1.2)
    ,legend.text=element_text(size=8))

This image is the population over time. But as you can see the dates on the x axis are incorrect and off:

This image is the population over time. But as you can see the dates on the x-axis are incorrect and off.

Upvotes: 2

Views: 19428

Answers (3)

Serhii
Serhii

Reputation: 422

Another way if your dates are imported in the correct order is to use

sumc$Date <- factor(sumc$Date, levels = unique(sumc$Date))

before plotting.

Upvotes: 1

Gregor Thomas
Gregor Thomas

Reputation: 145805

Convert to a Date class:

sumc$Date = as.Date(sumc$Date, format = "%m/%d%/Y")

Then your same plotting code will work just fine.

See ?as.Date or strptime for details about the conversion or the format argument.

Upvotes: 4

Ricardo A.
Ricardo A.

Reputation: 156

If your dates are imported in the correct order in the data frame, use

sumc$Date <- factor(sumc$Date, ordered = T)

prior to plotting. This will make them as ordered factors based on the order they appear, and ggplot will understand that it has to keep them that way.

Edit: if the dates are not ordered, you can order them and save to a vector:

dates <- unique(sort(sumc$Date))
sumc$Date <- factor(sumc$Date, labels = dates,  ordered = T)

Upvotes: 1

Related Questions