In R I have a data frame with bid and ask prices for a single day. Here is an example:
TimeHM; Bid_Price1; Ask_Price1
08:12; 101; 102
08:13; 101; 102
08:14; 102; 104
…
17:05; 104; 105
So, each new row is a new minute. Variable TimeHM is a character, while Bid_Price1 and Ask_Price1 are numeric.
I would like to plot Bid and ask prices for the whole day, and I would like to mark “10:00” with a vertical line. Here is my code:
ggplot(MyData, aes(x=TimeHM)) +
geom_line(aes(y=Bid_Price1, group=1)) +
geom_line(aes(y=Ask_Price1, group=1)) +
geom_vline(xintercept = "10:00", color="red", linetype="dashed") +
xlab("Time") + ylab("Price") + theme_classic(base_size = 20)
It works (also the vertical line), and “group=1” is also necessary for some reason. But the problem is that on the x-axis it labels each observation (for each minute). Instead I want to label some specific points in time, e.g. 9:00; 12:00; 15:00.
I have tried different solutions by googling. I guess the problem is that it does not see TimeHM as time. So, I tried the following before the ggplot:
MyData$TimeHM <- as.POSIXct(strptime(MyData$TimeHM, format="%H:%M"))
But then for some reason it adds the date of today, and then uses the time. For example, the first line suddenly becomes “07-25-2024 08:12:00”. Then I tried to add one of the following to the ggplot:
#scale_x_datetime(labels = date_format("%H:%M"))
#scale_x_date(labels = date_format("%H:%M"))
#scale_x_datetime(labels = label_date("%H:%M"))
It simply gives me an error. Somehow I once managed to plot it with scale_x_datetime, but both curves (bid and ask) were shifted to the left such that the first price was before 8:00 (while the dataset starts after 8:00). I have also tried with as_hms.
Can someone help? What is the right way to do it?
Thank you!