Reputation: 13
I want to put a text on an especific point in an histogram plot
ggplot(ECOBICI2) +
aes(x = Fecha_Arribo) +
geom_histogram(binwidth = 1) +
geom_text(aes(x = 2020-03-24), y = 12000, label = "Inicio de cierre de actividades") +
labs(x = "Dia", y = "Viajes Por Día") +
theme_classic()
It gives me this error Error: Invalid input: date_trans works with objects of class Date only
Fecha_Arribo are dates
I tried to put an as.Date()
ggplot(ECOBICI2) +
aes(x = Fecha_Arribo) +
geom_histogram(binwidth = 1) +
geom_text(aes(x = as.Date(2020-03-24, "%Y/%m/%d"), y = 12000, label = "Inicio de cierre de actividades") +
labs(x = "Dia", y = "Viajes Por Día") +
theme_classic()
Then it gives me this error Error in charToDate(x) : character string is not in a standard unambiguous format
Upvotes: 1
Views: 963
Reputation: 39595
As mentioned by @heds1 you have to specify the proper format for data using quotes and the structure of year, month and day so that the as.Date()
function can recognize it as date. Another point is that you must specify the x
,y
and label
values inside the aes()
option for geom_text()
. I have replicated a example for you using some dummy data. For sure in your real data you can change the values in geom_text()
to obtain the desired plot. Here the code:
library(ggplot2)
#Data
df <- data.frame(Fecha_Arribo=sample(seq(as.Date('2020-01-01'),
as.Date('2020-10-01'),
by='1 day'),500,replace = T))
Next the code for plot, I have also added a vertical line if you want to consider that option in your plot:
#Plot
ggplot(df,aes(x=Fecha_Arribo))+
geom_histogram(binwidth = 1) +
geom_text(aes(x = as.Date('2020-03-24'),y=8,label = "Inicio de cierre de actividades"))+
geom_vline(xintercept = as.Date('2020-03-24'),lty='dashed')+
labs(x = "Dia", y = "Viajes Por Día") +
theme_classic()
Output:
Upvotes: 0
Reputation: 3438
There are two things wrong here. Firstly, your format
argument to as.Date
does not match the format that you supply; you're telling it to parse a date delimited with forward slashes "/", but the date object that you supply is delimited by hyphens "-". Secondly, you're passing the date as a variable (with an impossible name, i.e., 2020-03-24), rather than as a string.
So, pass the date as a string, and supply the correct format
argument to as.Date
, e.g.:
as.Date('2020-03-24', '%Y-%m-%d')
Upvotes: 0