首页 文章

geom_rect和ggplot2错误:美学必须是长度1或与数据相同(2)

提问于
浏览
1

我想尝试像_2566964这样的东西,但我得到了错误

错误:美学必须是长度1或与数据(2)相同:xmin,xmax,ymin,ymax,x,y

'(2)'是什么意思?

涉及什么'Aesthetics'?我在 ggplot 中有 aesgeom_rect aes 但我不知道如何纠正它们......恐怕我永远不会 grab ggplot ...

days<-rep(Sys.Date(),100)+seq(1,100)
v<-sin(as.numeric(days))
df<-data.frame(days=days,v=v)

shade <- data.frame(x1=c(as.Date('2017-10-15'),as.Date('2017-11-11')), 
                   x2=c(as.Date('2017-10-20'),as.Date('2017-11-13')), 
                   y1=c(-Inf,-Inf), y2=c(Inf,Inf))

library(ggplot2)
plot(ggplot(df,aes(x=days,y=v))
     +geom_line()
     +geom_rect(data=shade, 
               mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), color='grey', alpha=0.2)
     +geom_point())

1 回答

  • 2

    geom_rect 一行试图从顶线 ggplot(df, aes(x = days, y = v)) 继承默认美学 .

    以下将有效:

    ggplot(df, aes(x=days, y=v)) +
      geom_line() +
      geom_rect(data=shade, inherit.aes = F,
                aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), 
                color = 'grey', alpha=0.2) +
      geom_point()
    

    enter image description here

    (我在代码中添加了更多的换行符/空格以便于阅读 . 另外,不需要在 plot() 中包装整个ggplot对象 . )

相关问题