2017-04-20 61 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