Please I need your help to find the error in this code. I am receiving the following error message: Error: Invalid input: date_trans works with objects of class Date only
. I think the problem is with scale_x_date
arguments, but I am unable to fix it. Thank you.
library(ggplot2)
library(scales)
library(lubridate)
library(readxl)
entrada<- read_excel("R_codes_examples/entrada_turistas.xlsx", sheet = "mensal", col_types =
c("date", "numeric"))
ggplot(entrada, aes(x = entrada$`mes_ano`, y = entrada$`movimento_de_passageiros`))
geom_line( colour = "#0c4c8a")
scale_x_date(date_breaks = "6 months",labels = date_format("%b-%Y"),limits = c(as.Date("2006-
08-01"), NA))
scale_y_continuous(labels=function(n){format(n, scientific = FALSE)})
labs(y= "Movimento de Passageiros mensais 2006 a 2017 ", x = "Mês/Ano")
xlab("")
theme(axis.text.x=element_text(angle=60, hjust=1))
Please find the head of my code below:
> dput(head(entrada))
structure(list(mes_ano = structure(c(1136073600, 1138752000,
1141171200, 1143849600, 1146441600, 1149120000), tzone = "UTC",
class = c("POSIXct", "POSIXt")), movimento_de_passageiros =
c(119764, 100442, 114198,
124676, 113431, 115482)), row.names = c(NA, -6L), class =
c("tbl_df", "tbl", "data.frame"))
CodePudding user response:
There are a few things that went wrong and yes your data was correct :)
- Change
labels = date_format("%b-%Y")
todate_labels = "%b-%Y"
- Your limits cannot contain one NA value as where does it need to stop? this cannot be an infinite date.
- Limits must be in
POSIXct
format - Just some code style things,
entrada$'mes_ano'
is not needed as you already passed the data and you can call x and y just by its name.
So here the fixed code assuming you work with POSIXct data (including time):
ggplot(entrada, aes(x = mes_ano, y = movimento_de_passageiros))
geom_line(colour = "#0c4c8a")
scale_x_datetime(date_breaks = "6 months", date_labels = "%b-%Y", limits = c(as.POSIXct("2006-01-01"), as.POSIXct("2006-12-01")))
scale_y_continuous(labels=function(n){format(n, scientific = FALSE)})
labs(y= "Movimento de Passageiros mensais 2006 a 2017 ", x = "Mês/Ano")
xlab("")`
Here an example if you work with as.Date dates, then make sure all has the same format
ggplot(entrada, aes(x = as.Date(mes_ano), y = movimento_de_passageiros))
geom_line(colour = "#0c4c8a")
scale_x_date(date_breaks = "6 months", date_labels = "%b-%Y", limits = c(as.Date("2006-01-01"), as.Date("2006-12-01")))
scale_y_continuous(labels=function(n){format(n, scientific = FALSE)})
labs(y= "Movimento de Passageiros mensais 2006 a 2017 ", x = "Mês/Ano")
xlab("")