In R, a date must consist of a year, month, and day. A single number like 2000 cannot be converted to Date. If you change the years to “2020-01-01”, then they can be handled like a date (1 Jan 2020).
It is possible that you do not actually need the years as dates - you provide more information about what plot you are trying to make, or some of your R code, then it may be easier for us to help.
To quickly convert years alone (e.g. 2020) to dates (as 2020-01-01) you could write code like this:
data <- data %>%
mutate(year = as.Date(str_glue({year}-01-01))
Below I have provided an example of applying this code to a numeric year column.
Let us know if this helps!
Neale
#load packages
library(tidyverse)
# make example data
data <- tribble(
~year,
2020,
2020,
2020,
2021,
2021,
2021,
2021
)
# view example data
data
#> # A tibble: 7 × 1
#> year
#> <dbl>
#> 1 2020
#> 2 2020
#> 3 2020
#> 4 2021
#> 5 2021
#> 6 2021
#> 7 2021
# check class of year column
class(data$year)
#> [1] "numeric"
# change class to Date by adding "-01-01" after the year
data <- data %>%
mutate(year_dt = as.Date(str_glue("{year}-01-01")))
# check class of new date column
class(data$year_dt)
#> [1] "Date"
# look at data
data
#> # A tibble: 7 × 2
#> year year_dt
#> <dbl> <date>
#> 1 2020 2020-01-01
#> 2 2020 2020-01-01
#> 3 2020 2020-01-01
#> 4 2021 2021-01-01
#> 5 2021 2021-01-01
#> 6 2021 2021-01-01
#> 7 2021 2021-01-01
It sounds like the solution could be simple. Were you able to try converting the years to dates with the code I provided above?
If you can provide a small piece of your data and the complete R code, then maybe we see the problem can help you to troubleshoot. See this video for guidance on how to do this.
I believe, I am running into a similar issue. I’ve tried to find an example of what I am trying to do but have not had much luck. My problem is two fold, but the first issue shouldn’t be to difficult to figure out, but I clearly am not asking the correct question. I have trend data 2011 to 2022. My x axis is by year(numeric type) but the values come out as a decimal format and don’t align with my value. I’m guessing there is a way to set the break points, but I can’t seem to get the correct format.
I apologize I spoke to soon. I was able to find what I was looking for.
scale_x_discrete(limits = clean_fs$year) year is not a good column name which is why I have to reference my data set.