Show limited time range on x axis with ggplot

I want the x axis in the following chart to start at 06:00 and end at 22:00 with breaks every 4 hours. However, I cannot understand the following.

a) How to start the x axis at 06:00 without any empty space before 06:00.

b) How to make the end of the x axis at 22:00 without any empty space after 22:00. He doesn't even show right now 22:00

c) Like breaks every 4 hours.

d) How to assign a label to the y axis (currently it's just X4, the column name).

I tried several things, but to no avail. Some sample data:

range <- seq(as.POSIXct("2015/4/18 06:00"),as.POSIXct("2015/4/18 22:00"),"mins")

df <- data.frame(matrix(nrow=length(range),ncol=4))
df[,1] <- c(1:length(range))
df[,2] <- 2*c(1:length(range))
df[,3] <- 3*c(1:length(range))
df[,4] <- range

Reshape:

library(reshape2)
df2 <- melt(df,id="X4")

Graph:

library(ggplot2)
ggplot(data=df2,aes(x=X4,y=value,color=variable)) + geom_line()+
  scale_y_continuous(expand=c(0,0)) +
  coord_cartesian(xlim=c(as.POSIXct("2015/4/18 06:00:00"),as.POSIXct("2015/4/18 22:00:00")))

What makes a chart like this: enter image description here

Any ideas?

+4
source share
1 answer

. scale_x_datetime.

## desired start and end points
st <- as.POSIXct("2015/4/18 06:00:00")
nd <- as.POSIXct("2015/4/18 22:00:00")

## display data for given time range
ggplot(data = df2, aes(x = X4, y = value, color = variable)) + 
  geom_line() +
  scale_y_continuous("Some name", expand = c(0, 0)) +
  scale_x_datetime("Some name", expand = c(0, 0), limits = c(st, nd), 
                   breaks = seq(st, nd, "4 hours"), 
                   labels = strftime(seq(st, nd, "4 hours"), "%H:%S"))

ggplot

+4

All Articles