r - 在 `geom_hline` 图中设置 `geom_bar` 的长度

标签 r time ggplot2 stack

我有一个 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 如果我尝试使用 pos 将其绘制为 as.numeric,

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

我收到此错误,

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

如何设置绿线的长度?

最佳答案

您可以将 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")

关于r - 在 `geom_hline` 图中设置 `geom_bar` 的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15392570/

相关文章:

read.table 和解析 R 中的 float 据

java - 将时间戳(以毫秒为单位)转换为 Java 中的字符串格式时间

linux - 什么是CPU系数?

r - 将行名称设置为 R 中的多个矩阵

r - R中代数关系的笛卡尔积表

r - 沿 x 轴具有完整数据和子集的 ggplot

r - GTrendsR + ggplot2?

R:从 ggplot 对象中提取比例名称

r - 如何重命名由R中的循环索引的元素列表

performance - 如何将准确度绘制为 Keras 中处理时间的函数?