【问题标题】:set length of `geom_hline` in `geom_bar` plot在“geom_bar”图中设置“geom_hline”的长度
【发布时间】:2013-03-01 19:35:15
【问题描述】:

我有一个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 

还有剧情,

如果我尝试用pos 将其绘制为as.numeric

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

我收到此错误,

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

如何设置绿线的长度?

【问题讨论】:

  • 如果您想更好地控制长度,请使用geom_segment。警告不是错误。不要混淆两者!
  • 谢谢,很好,这是一个警告。

标签: r time ggplot2 stack


【解决方案1】:

您可以将geom_hline() 替换为geom_segment(),并为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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2015-02-16
    • 2011-04-26
    • 2022-08-18
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    相关资源
    最近更新 更多