【问题标题】:Partially shaded background for ggplotly-objectggplotly-object 的部分阴影背景
【发布时间】:2017-09-17 15:36:54
【问题描述】:

我正在尝试使用 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 获得这种阴影呢?不幸的是,在情节中重新创建整个情节是不可能的。

谢谢!

【问题讨论】:

    标签: r ggplot2 plotly


    【解决方案1】:

    如上一个答案所引用的,我们可以通过plot[['x']][['layout']][['shapes']]访问形状,然后使用函数layout(...)创建新形状。

    但是plot &lt;- 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(..) 功能的其他人有所帮助。

    【讨论】:

      【解决方案2】:

      为了使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
               )
             )
      )
      


      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` orgplot`` 改变了它处理日期的方式。现在不需要传递字符串日期,而是需要传递整数,即它应该是:

      x0 = 315532800000, x1 = 631152000000
      

      得到正确的结果。

      【讨论】:

      • 这太不可思议了,我从来没有想到过。非常感谢!
      猜你喜欢
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 2011-07-20
      • 2012-06-25
      相关资源
      最近更新 更多