Starting point of axis X using scale_x_date()

Asked

Viewed 117 times

3

I am making a stacked area chart and use the following code

ggplot(gdados, aes(Commissioned, acum, fill = Country)) +
  geom_area(col=c('black')) +
  scale_fill_brewer(palette = "Paired")+
  scale_x_date(breaks= "10 years", labels = date_format("%Y"), limits = c(as.Date('1920-01-01'),as.Date('2020-01-01')))+
  labs(x = "Ano", y = 'Potência Instalada [MW]', fill = NULL) +
  scale_y_continuous(breaks=seq(0,160000,10000)) +  
  theme_minimal()

The reference on the x-axis begins to be shown from 1924 and ends in 2024, with breaks every 10 years. How do I start in the year 1920 and, with the breaks every 10 years, finish in 2020 the last break?

1 answer

2


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")

inserir a descrição da imagem aqui

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))

inserir a descrição da imagem aqui

It is important to note that when creating this sequence of dates we indicate:

  1. On what date it began (January 1920)
  2. The size of the "jumps" between a date and another (10 years)
  3. 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!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.