Reputation: 279
I want to plot a line graph, with x axis time (hh:mm)(this is a specific time interval), and y axis average price.
I want the graph to display multiple lines (one line for each day).
Currently my data frame is like this (I have some other variables as well but I am not using them in my graph. the relevant ones are below):
AV.PRICE DATE TIME
180 2014-01-20 13H 0M 0S
179 2014-01-20 13H 1M 0S
175 2014-01-20 13H 2M 0S
179 2014-01-20 13H 3M 0S
...and so on, the dates continue but the times only take on values between 13:00 and 15:00 each day
The DATE class is date, AV.PRICE is num, TIME is period (used lubridate)
if my question isnt clear, this is what i'm looking for, plotting a date-agnostic graph on a time only axis, except i'm using ggplot2 in r: plotting data for different days on a single HH:MM:SS axis
EDITED:
when i try to plot the original df with ggplot, it does not recognize the time variable. ggplot(df, aes(x=TIME, y=AV.PRICE, group = DATE)) + geom_line()
gives error: cannot compare Period to Duration
dput
structure(list(AV.PRICE = c(178.841368677043, 178.837478586724,
178.811640304183, 178.8395125, 178.858236768802, 178.860812464589
), DATE = structure(c(16098, 16098, 16098, 16098, 16098, 16098
), class = "Date"), TIME = structure(c(0, 0, 0, 0, 0, 0), year = c(0,
0, 0, 0, 0, 0), month = c(0, 0, 0, 0, 0, 0), day = c(0, 0, 0,
0, 0, 0), hour = c(13, 13, 13, 13, 13, 13), minute = c(0, 1,
2, 3, 4, 5), class = structure("Period", package = "lubridate"))), .Names = c("AV.PRICE",
"DATE", "TIME"), row.names = c(NA, 6L), class = "data.frame")
Upvotes: 2
Views: 2697
Reputation: 10671
I think you problem is with having df$TIME
class = "Period", instead of time. All you need to do it coerce it back to POSIXt.
df <- data.table::fread("AV.PRICE DATE TIME
180 2014-01-20 13H0M0S
179 2014-01-20 13H1M0S
175 2014-01-20 13H2M0S
179 2014-01-20 13H3M0S
182 2014-01-21 13H0M0S
181 2014-01-21 13H1M0S
177 2014-01-21 13H2M0S
181 2014-01-21 13H3M0S")
I added an extra value for Date with shifted AV.PRICE
for display purposes. Sorry I couldn't get your dput
to load properly or I would have started from there. Also fread
doesn't like spaces in the input, but you could use something like collapse
and as.character
on your actual df$TIME column.
df$TIME %<>% lubridate::parse_date_time("HMS") # make it class = "POSIXt
ggplot(data = df, aes(x = TIME, y = AV.PRICE, color = DATE)) +
geom_line()
You could play around with + scale_x_time()
if you want too, but the default looks like it is rendering your desired output.
Upvotes: 4