There seems to be a lot of posts where you want to change the date in ggplot for a specific time-period, and that's easy if you want to just combine some date - however, I want to:
- (preferably) set the start value to be the max value of my Date-column (which is in date-format) subtracted by 2 yr or 18/24 months.
- if 1 is not feasible, set the start year (and or year and month) and get the x-axis to continue to the latest date in my df.
How do I achieve this?
Thanks!
EDIT: My df:
> str(df_konj)
'data.frame': 1950 obs. of 3 variables:
$ Indikator: Factor w/ 6 levels "Barometerindikatorn",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Period : Date, format: "1996-01-01" "1996-02-01" "1996-03-01" "1996-04-01" ...
$ value : num NA NA NA NA NA NA 85.6 88 88.9 91 ...
The "Indikator" col. has 6 series that each is and individual line in the ggplot, since this series is updated through API with new month monthly I need the ggplot to show moving dates - I can not specify the date in "YYYY-MM-DD"-format which all the post I found basically refers to.
The ggplot:
ggplot(df_konj, aes(x = Period, y = value, group=Indikator, color=Indikator,
linetype=Indikator, linewidth = Indikator)) +
geom_point() +
geom_line()
The solution in my head
Some code that says 1. let the end date of x-axis to be the max of the date-col. called "Period" (I think I know that the max value can be extracted by max(Period)
- since it's in Date-format 2. and create a variable or do it in the argument that the min x-value is the max-value subtracted by z months - I think this is also possible to do with Date-format objects (but don't remember how). Anyways even if I had the variables I don't know how to pass it into ggplot.
EDIT2 - a solution
This worked, although I'm not sure it's the smartest way of generating the mindate variable - I found a I function on stackoverflow (to subtract months), but it keeps both old and new date, so an additional step is necessary
maxdate <- max(df_konj$Period)
add.months = function(date,n) seq(date, by = paste (n, "months"), length = 2)
mindate <- add.months(maxdate, -18)
mindate <- mindate[2]
Code, which use the logic all(?) post related to specifying exakt dates do:
scale_x_date(limits=(c(mindate, maxdate))