0

I'm trying to plot 5 days of historical stock data in R using ggplot. Datetime on the x axis, and the stock values ('close') on the y axis. I only want to show the minutes of the day when the stock market is open, and my data set is limited to 7 hours a day of values x 5 days.

But when I plot it with ggplot, the scale is changed so I get all the hours per day.

ggplot(data = df_stock, aes(x = datetime, y = close)) +
  geom_line()

I've tried googling this and using the R help function. I'm quite new to R so my apologies if this is very easy to solve. I hope someone can guide me in the right direction.

Jaap
  • 81,064
  • 34
  • 182
  • 193
rc_tn
  • 57
  • 1
  • 8
  • 1
    Welcome to StackOverflow! Please read the info about how to produce a [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). This will make it much easier for others to help you. – Jaap Sep 21 '14 at 12:00

1 Answers1

4

While a minimal example would be helpful to address this question, a more general answer which could be useful can be given.

ggplot2 does not have a facility for axis-breaking, as it's not considered good practice. However what you're doing here is actually a transformation of the variable --- hours open rather than hours of the day. So you'll have to transform the variable itself. You can do this using the lubridate package. Let's take two days and imagine the market is open between 10am and 5pm.

require(lubridate)
dates <- c("2014-01-01 10:00:00 UTC", "2014-01-01 13:00:00 UTC", "2014-01-01 17:00:00 UTC", "2014-01-02 13:00:00 UTC", "2014-01-02 17:00:00 UTC")
dates <- ymd_hms(dates)

Now you will need to scale the data to only have the times you want. You can call the parts of the date with `lubridate', and divide by the hours in the day, where here they are 24 rather than 7.

hour(dates) <- hour(dates)-10
scaleddates <- day(dates)-1 + hour(dates)/7 + minute(dates)/60/7 + second(dates)/60/60/7
scaleddates
[1] 0.0000000 0.4285714 1.0000000 1.4285714 2.0000000

Now you can plot the graph, with the x-axis reading 'Days' rather than 'Dates'. The x-axis is now how far you are through the working day.