Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplotly对象的部分着色背景_R_Ggplot2_Plotly - Fatal编程技术网

R ggplotly对象的部分着色背景

R ggplotly对象的部分着色背景,r,ggplot2,plotly,R,Ggplot2,Plotly,我正在尝试使用ggplot2创建时间序列的线图,并将其转换为plotly。此绘图的一部分背景应该以不同的颜色进行着色(如下图所示:)。不幸的是,annotate()和geom_rect并没有像看上去那样传输到ggplotly对象。因此,我尝试使用plotly代码(基于此示例:)追溯添加形状,但也不起作用,如此可复制示例所示: library(plotly) library(ggplot2) plot <-ggplot(data = economics, aes(x = date, y =

我正在尝试使用ggplot2创建时间序列的线图,并将其转换为plotly。此绘图的一部分背景应该以不同的颜色进行着色(如下图所示:)。不幸的是,annotate()和geom_rect并没有像看上去那样传输到ggplotly对象。因此,我尝试使用plotly代码(基于此示例:)追溯添加形状,但也不起作用,如此可复制示例所示:

library(plotly)
library(ggplot2)

plot <-ggplot(data = economics, aes(x = date, y = unemploy)) + geom_line() 

plot <- ggplotly(plot)

layout(plot,
       shapes = list(
         list(type = "rect",
              fillcolor = "blue", line = list(color = "blue"), opacity = 0.9,
              x0 = "1980-01-01", x1 = "1990-01-01",
              y0 = 0, y1 = 4000
         )
       )
)
library(plotly)
图书馆(GG2)

绘图为了使
ggplotly
与形状一起工作,您需要首先清除来自转换的形状(我不明白它们为什么会在第一位)



为了得到正确的结果。

如前一个答案所述,我们可以通过
绘图[['x'][[['layout']][['shapes']]]
访问形状,然后使用函数
布局(…)
创建新形状


但是
的情节太不可思议了,我从来没有想到过。非常感谢你!
plot[['x']][['layout']][['shapes']] <- c()
plot <- layout(plot,
       shapes = list(
         list(type = "rect",
              fillcolor = "blue", line = list(color = "blue"), opacity = 0.9,
              x0 = "1980-01-01", x1 = "1990-01-01",
              y0 = 0, y1 = 4000
         )
       )
)
library(plotly)
library(ggplot2)

plot <-ggplot(data = economics, aes(x = date, y = unemploy)) + geom_line()
plot <- ggplotly(plot)

plot[['x']][['layout']][['shapes']] <- c()

plot <- layout(plot,
       shapes = list(
         list(type = "rect",
              fillcolor = "blue", line = list(color = "blue"), opacity = 0.5,
              x0 = "1980-01-01", x1 = "1990-01-01",
              y0 = 6000, y1 = 8000
         )
       )
)
plot
x0 = 315532800000, x1 = 631152000000
plot[['x']][['layout']][['shapes']] <- list(
              list(type = "rect",
                   fillcolor = "lightgreen", line = list(color = "lightgreen"), opacity = 0.3,
                   x0 = 0, x1 = 30, xref = "x",
                   y0 = -100, y1 = 100, yref = "y"))