First of all, we will create the data that will be used to reproduce the problem and then to demonstrate the solution.
set.seed(123)
dados <- data.frame(data = seq(Sys.Date(), by = "-1 year", length.out = 100),
val = rnorm(100, 100, 15))
With that object dados
, we can create a chart with similar problems with the code below:
library(ggplot2)
ggplot(dados, aes(data, val)) +
geom_line() +
scale_x_date(date_labels = "%Y", breaks = "10 years")
As noted in the image, there is the problem that, despite 10 years of inverting between a tick and another, they are not in the Multiplus of 10 (1930, 1940, etc...).
To resolve this we can indicate those dates that should appear in ticks with the argument breaks
. We can create these dates with the function seq
(me mode similar to the one made to create the data). So we would have
ggplot(dados, aes(data, val)) +
geom_line() +
scale_x_date(date_labels = "%Y",
breaks = seq(as.Date("1920-01-01"), by = "10 years", length.out = 11))
It is important to note that when creating this sequence of dates we indicate:
- On what date it began (January 1920)
- The size of the "jumps" between a date and another (10 years)
- How large the sequence should be (11 elements)
There are other ways to create these sequences, including an object that the sequence must follow (i.e., having the same size), argument along.with
, or indicate the date when the sequence must end, argument to
.
Solved and understood. Thank you very much!
– Matheus Dias