0

Currently using ggplot2 and scales doing this but would be ideal to show a date range +/- 1 Year (for example). I shouldn't really be hardcoding these dates as it's not very efficient.

library(scales) #date time scales
library(ggplot2) # Visualization

ggplot(dataset,aes(x=datetime_start, y=dataset$Product, color=Stage, order = - as.numeric(Stage))) +
geom_segment(aes(x=From,xend=To,yend=dataset$Product), size=10) +
scale_x_datetime(
breaks = date_breaks("1 month"), 
labels=date_format("%b%y"),
limits = c(
      as.POSIXct("2016-03-01"),
      as.POSIXct("2018-02-01")
) 
) +
Jared Pace
  • 41
  • 7

1 Answers1

1

Expand the scale:

library(ggplot2)
df <- data.frame(x = seq(Sys.Date()-lubridate::years(2), Sys.Date(), by="3 month")) 
df$y <- 1:nrow(df)
p <- ggplot(df, aes(x, y)) + geom_line()
p + scale_x_date(expand = c(0, 365))
lukeA
  • 53,097
  • 5
  • 97
  • 100
  • Looks like you also need the lubridate package, no? – Jared Pace Jul 20 '17 at 21:45
  • This looks good, just confused how it fits into my current code. Have tried to make it work but can't. Could you help clarify how it fits into what I have currently? – Jared Pace Jul 20 '17 at 22:00
  • @JaredPace Please edit your post and provide a [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#answer-5963610) of what you got, like asked by the R tag (hover over it). Then one can see what you currently have and why the above does not work. (I guess it's because I used dates and you got times, so you would need to do 60*60*24*365 (seconds*minutes*hours*days per year instead of just 365 days). – lukeA Jul 20 '17 at 23:56