2013-03-13 26 views
2

我有一個geom_bar圖,我想設置長度爲geom_hline`geom_bar`中的`geom_hline`的設置長度圖

我有這樣的數據,

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 

,然後我嘗試這樣

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 

這給錯誤信息繪製它,

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

和劇情,

ddd 如果我嘗試用posas.numeric繪製它,

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

我得到這個錯誤,

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

如何設置綠線的長度是多少?

+1

如果你想更好地控制長度使用'geom_segment'。並且警告不是錯誤。不要混淆兩者! – joran

+0

謝謝,好點,這是一個警告。 –

回答

4

您可以用geom_segment()替換geom_hline(),並將x的值設置爲起始和結束位置。

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")