Casper Quint
Casper Quint

Reputation: 19

Removing nighttime from x-axis in ggplot (R)

I'm trying to plot second data using ggplot2. I'm looking at data over multiple days. Data is only available from 9:30AM to 17:00PM however. How can I exclude nighttime data from my graph?

Following code gives me the graph below:

ggplot(data=combined_total,aes(x=times, y=difference_adjustedforex)) + 
  geom_path(colour="red") + 
  ylab("Difference in price adjusted for exchange rate in USD") + 
  xlab("Time") +
  labs(title = paste("Second data price difference between", stock1, "and", stock2))

PLOT

Upvotes: 0

Views: 284

Answers (1)

Jon Spring
Jon Spring

Reputation: 66815

I think facets might be the simplest way to get a discontinuous axis.

# Making fake data with gaps like OP data
set.seed(1)
fake_data <- data.frame(
  times = seq.POSIXt(from = as.POSIXct("2019-04-01 00:00"),
                     to   = as.POSIXct("2019-04-03 23:55"), by = 60*5),
  difference = rnorm(864, 0, 1)
)
fake_data <- subset(fake_data, hour >= 9.5 & hour <= 17)

Plotting it to confirm it's structurally similar to your data:

ggplot(data=fake_data,aes(x=times, y=difference)) + 
  geom_path(colour="red") + 
  ylab("Difference in price adjusted for exchange rate in USD") + 
  xlab("Time") +
  labs(title = paste("Second data price difference"))

enter image description here

Let's add a day variable to control which facet we plot to, and then change the x axis from datetime to numeric. That will make it a little easier to show a consistent range of hours in each facet, even if the data does not span all those hours.

fake_data$day = lubridate::as_date(fake_data$times)

ggplot(data=fake_data,aes(x=hour, y=difference)) + 
  geom_path(colour="red") + 
  ylab("Difference in price adjusted for exchange rate in USD") + 
  xlab("Time") +
  labs(title = paste("Second data price difference")) +
  coord_cartesian(xlim = c(9.5, 17)) +
  facet_wrap(~day, nrow = 1)

enter image description here

Upvotes: 3

Related Questions