3

I have an geom_bar plot and I would like to set the length of the geom_hline.

I have this data,

set.seed(666)
df <- data.frame(
  date = seq(Sys.Date(), len= 156, by="4 day")[sample(156, 26)],
  IndoorOutdoor = rep(c(-1,1), 13), #Change so there are only 26 rows
  Xmin = sample(90, 26, replace = T),
  Ymin = sample(90, 26, replace = T),
  Zmin = sample(90, 26, replace = T)
)

df$XYZmin <- rowSums(df[,c("Xmin", "Ymin", "Zmin")])*df$IndoorOutdoor
df[,7:9] <- df[,3:5]*df[,2] #Adding the sign to each X/Y/Z
names(df)[7:9] <- paste0(names(df)[3:5],"p") #to differentiate from your X/Y/Z
require(ggplot2)

df.m <- melt(df[,c(1:2,6:9)], measure.vars=c("Xminp", "Yminp", "Zminp"))
df.m$pos <- c(as.Date("2013-04-15"), rep(Sys.Date(), (length(df.m$XYZmin)-1)))
df.m$foo <- 0

and then I try plotting it like this

plot.alt <- ggplot(df.m, aes(date, value, fill=variable)) + 
  geom_bar(position="stack", stat="identity", width=0.5) + 
  geom_hline(aes(pos, foo), size = 0.8, colour = "green")
plot.alt

this gives the error message,

Warning message:
Stacking not well defined when ymin != 0 

and the plot,

ddd if I try plotting it with pos as as.numeric,

df.m$pos <- as.numeric(df.m$pos)

I get this error,

Error: Invalid input: date_trans works with objects of class Date only

How can I set the length of the green line?

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
Eric Fail
  • 8,191
  • 8
  • 72
  • 128

1 Answers1

7

You can replace geom_hline() with geom_segment() and set your starting and ending positions for x values.

ggplot(df.m, aes(date, value, fill=variable)) + 
  geom_bar(position="stack", stat="identity", width=0.5) +
  geom_segment(aes(x=min(pos),xend=max(pos),y=0,yend=0),colour="green")
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201