J. Doe
J. Doe

Reputation: 43

ggplot2 timeseries plot through night with non-ordered values

a = c(22,23,00,01,02) #hours from 22 in to 2 in morning next day
b = c(4,8,-12,3,5) #some values
df = data.frame(a,b)

When I plot this data with ggplot2 it sorts the first column a, but I don't want it to be sorted.

The code used in ggplot2 is ggplot(df, aes(a,b)) + geom_line()

ggplot plot of timeseries and data

In this case, the X-axis is sorted and they are providing wrong results like

hour 0 consists of value 4, and the truth is that hour 22 consist of value 4

Upvotes: 0

Views: 218

Answers (1)

Roman
Roman

Reputation: 76

R needs to somehow know that what you provide in vector "a" is a time. I have changed your vector slightly to give R the necessary information:

a = as.POSIXct(c("0122","0123","0200","0201","0202"), format="%d%H") 
# hours from 22 in to 2 in morning next day (as strings)
# the day is arbitrary but must be provided
b = c(4,8,-12,3,5) #some values
df = data.frame(a,b)
ggplot(df, aes(a,b)) + geom_line()

Plot with values ordered by correct time

You can use paste() to glue days and hours together automatically (e.g. paste(day,22,sep=""))

Upvotes: 1

Related Questions