2017-04-20 100 views
1

我试图用ggplot2创建时间序列的线图并将其转换为绘图。这个阴谋的背景的一部分应该被用不同的颜色阴影(像这个:Using geom_rect for time series shading in R)。不幸的是,annotate()以及geom_rect并不像它看起来那样被转移到ggplotly对象。因此,我试图追溯添加使用plotly代码(基于这个例子:https://plot.ly/r/shapes/)的形状,但它不工作或者,如在此重复的例子:ggplotly-object的部分阴影背景

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

所以,我怎么能得到这个底纹我的gplotly对象?不幸的是重新创建整个剧情是不可能的。

谢谢!

回答

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 

,以获得正确的结果。

+0

这是不可思议的,我从来没有想到这一点。非常感谢! – aeq