0

I am making a step graphic of "inventary levels" and I want to include horizontal segments at the level 5 in Y. So, I am importing my table from Excel. The first of the two columns has Dates with the format "2020-12-04" and R reads it very well.

I plot the data using geom_step and it works perfectly, the X axis becomes the dates and the Y axis is the inventory level.

The problem is when I try to add a segment between to dates using geom_segment(aes(x=2020-12-04, y=5, xend=2020-12-12, yend=5 )) it shows me:

Error: Invalid input: time_trans works with objects of class POSIXct only

How can I fix this? Here is the code I am using

Datos<-read_excel(ruta_excel, sheet="CDSYG", range="J4:K45")
    
p<-ggplot(data=Datos, aes(x=Dia, y=Nivel))
    
p+geom_step()+geom_segment(aes(x=2020-12-04, y=5, xend=2020-12-12, yend=5 ))
stefan
  • 90,330
  • 6
  • 25
  • 51
  • 2
    Try with quotes `geom_segment(aes(x="2020-12-04", y=5, xend="2020-12-12", yend=5 ))` or `geom_segment(aes(x=as.Date("2020-12-04"), y=5, xend=as.Date("2020-12-12"), yend=5 ))`. But it would be easier to help you with an example of the data you are working with. – Phil Sep 02 '21 at 02:01
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 02 '21 at 02:10
  • My data is in a sheet of Excel and the values it has in the cells are: 04/12/2020 ... 13/01/2021 in a column. Every date has an integer besides: 24, 24, 23...42 When I imported these values using "read_excel", it was imported as a data.frame with this aspect 2020-12-04 00:00:00, and when I use class(Datos$Dia) I get "POSIXct" "POSIXt". Basically I want to put a segment between 2020-12-04 and 2020-12-12 at the 5-level in the Y axis. The arguments of geom_segment are the coordinates x, y, xend yend, but I dont know the input of x and xend since they are dates in POSIXct format. – Francisco Daniel Quiroz Sep 02 '21 at 02:38

1 Answers1

0

Convert the dates where you want to draw the segment to a datetime:

BTW: To help us to help it would be easier to share a snippet of your data or use some fake data as I did. See how to make a minimal reproducible example. To post data type dput(NAME_OF_DATASET) into the console and copy & paste the output starting with structure(.... into your post. If your dataset has a lot of observations you could do dput(head(NAME_OF_DATASET, 20)) for the first twenty rows of data

library(ggplot2)

ggplot(data = Datos, aes(x = Dia, y = Nivel)) +
  geom_step() +
  geom_segment(aes(x = as.POSIXct("2020-12-04"), y = 5, xend = as.POSIXct("2020-12-12"), yend = 5), color = "red")

DATA

set.seed(42)

Datos <- data.frame(
  Dia = seq.Date(as.Date("2020-12-01"), as.Date("2020-12-31"), by = "day"),
  Nivel = sample(1:10, 31, replace = TRUE)
)
Datos$Dia <- as.POSIXct(Datos$Dia)
stefan
  • 90,330
  • 6
  • 25
  • 51