ggplotly-object的部分阴影背景

时间:2017-04-20 20:14:32

标签: r ggplot2 plotly

我正在尝试使用ggplot2创建时间序列的线图并将其转换为plotly。该图的背景的一部分应该以不同的颜色着色(例如:Using geom_rect for time series shading in R)。不幸的是,annotate()以及geom_rect并没有转移到ggplotly-object中。因此,我尝试使用plotly-code追溯添加形状(基于此示例:https://plot.ly/r/shapes/),但它也不起作用,如此可重现的示例中所示:

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

那么如何为我的ggplotly-object获取这个着色?遗憾的是,不可能在剧情中重新创造整个情节。

谢谢!

2 个答案:

答案 0 :(得分:0)

为了让ggplotly能够处理形状,您需要首先清除转换后的形状(首先打败我们为什么会这样)。

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

您需要将layout函数分配给plot对象。

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

enter image description here

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

更新:似乎plotly` or gplot``改变了它处理日期的方式。现在不需要传递字符串日期,而是需要传入整数,即它应该是:

x0 = 315532800000, x1 = 631152000000

获得正确的结果。

答案 1 :(得分:0)

如前面的回答所述,我们可以通过plot[['x']][['layout']][['shapes']]访问形状,然后使用函数layout(...)创建新形状。

plot <- layout(...)功能对我不起作用。 (抛出未使用的参数错误)因此,我尝试仅使用plot[['x']][['layout']][['shapes']]功能,并且它可以工作。

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

希望对那些无法使用layout(..)功能的人有所帮助。