How to convert the format of a Date vector without it changing to Character?

Asked

Viewed 29 times

1

I’m starting now on the R and getting beat up a lot with the Date class. I want to change the format "%Y-%m-%d" to "%b-%Y", but it also changes the class of the vector.

x.data1 <- as.Date(c("2016-11-01", "2016-12-01", "2017-01-01",
            "2017-02-01", "2017-03-01", "2017-04-01",
            "2017-05-01", "2017-06-01", "2017-07-01"),
            format = "%Y-%m-%d")

x.data <- format.Date(x.data1, format = "%b/%Y") 

I need to place this vector as the x-axis in Plot (ggplot), but the scale_x_continuous() function is not applicable to the Character class.

addendum: I’ve tried the lubridate and I’ve read several other questions here and in other sources... but nothing works :'(

1 answer

1


No need to convert the format before plotting the chart, the package ggplot2 recognizes class objects "Date" and using the arguments date_breaks and date_labels of scale_x_date the desired format is obtained.

library(ggplot2)

ggplot(dados, aes(x.data1, y)) +
  geom_point() +
  scale_x_date(date_breaks = "1 month", date_labels =  "%b/%Y") +
  theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust=1))

inserir a descrição da imagem aqui

Dice

x.data1 <- as.Date(c("2016-11-01", "2016-12-01", "2017-01-01",
                     "2017-02-01", "2017-03-01", "2017-04-01",
                     "2017-05-01", "2017-06-01", "2017-07-01"),
                   format = "%Y-%m-%d")
dados <- data.frame(x.data1, y = seq_along(x.data1))

Browser other questions tagged

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