0
votes

I have some data that I am plotting in ggplot and I would like to get the date on the x-axis to start earlier, so that I can compare it better with other graphs. Dummy data at the bottom.

###plot line graph

cell1 <- ggplot(df[!is.na(df$value), ], aes(x=Date, y=value,  colour 
=variable, group = variable,shape = variable, linetype = variable, fill 
= variable))
cell1 <- cell1 + geom_line(lwd =3) + geom_point(size =17, stroke = 2)

I want it to start from the 16-06-2018 and have weekly ticks to the 04-08-2016. I have been using break.vec() to some success, but because this data set starts closer (i.e. first data point on the 20-06-2016) to the second tick mark it is completely dropping the first and starting at the 23-06-2016. I am sure I am just missing something simple.

###adjust x-axis

break.vec <- c(as.Date("2016-06-16"),
           seq(from=as.Date("2016-06-16"), to=as.Date("2016-08-04"), 
by="week"))
cell1 <- cell1 + scale_x_date(breaks = break.vec, date_labels = "%d- 
%m",expand = c(0.05,0))

Any input appreciated

df <- structure(list(Date = structure(c(16968, 16969, 16970, 16971, 
16972, 16973, 16974, 16975, 16976, 16977, 16978, 16979, 16980, 
16981, 16982, 16983, 16984, 16985, 16986, 16987, 16988, 16989, 
16990, 16991, 16992, 16993, 16994, 16995, 16996, 16997, 16998, 
16999, 17000, 17001, 17002, 17003, 17004, 17005, 17006, 17007, 
17008, 17009, 17010, 17011, 17012, 17013, 17014, 17015, 17016
), class = "Date"), variable = structure(c(1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = 
"total.cell.L", class = "factor"), 
value = c(NA, NA, NA, NA, 64730L, NA, NA, NA, 138128L, NA, 
NA, NA, 64230L, 84194L, NA, 87666L, NA, NA, NA, NA, 8980L, 
NA, NA, NA, 24503L, NA, NA, 72042L, 55651L, NA, NA, NA, NA, 
17360L, NA, NA, NA, NA, 57287L, NA, NA, NA, 98081L, NA, 46003L, 
NA, 122385L, NA, 177067L)), row.names = c(NA, -49L), .Names = c("Date", 
"variable", "value"), class = "data.frame")
1
Adjust your expand vector to about c(0.1, 0) when you rescale the datecsgroen
Ahha that did it! Thank you.Lmm

1 Answers

2
votes

To get the exact start date that you want, use expand_limits. In the code below, we use the earliest date in break.vec as the starting value:

cell1 + 
  scale_x_date(breaks = break.vec, date_labels = "%d-%m") +
  expand_limits(x=min(break.vec))

Another way to set axis limits is the limits argument to scale_x_date:

cell1 + 
  scale_x_date(breaks = break.vec, date_labels = "%d-%m", limits=range(break.vec))

You can also use the expand argument in scale_x_date to control the amount of padding added to the x-axis, but limits and expand_limits gives you fine control over placement of the limits.