将布局参数传递给R Plotly中的子图

时间:2016-06-21 21:58:48

标签: r plotly

我试图突出显示一组图表中的各个图表。在下面的示例中,我想突出显示' cash_lvl'情节。如果您运行下面的代码,您会看到dat.plot.list [1]将显示一个红色背景的图表。但是,使用子图时,两个背景都是白色的。

有没有办法让背景在子图中正确显示?

library(dplyr)
library(plotly)

dat <- structure(
    list(
      date = structure(
        c(
          16101, 16129, 16160, 16190,
          16221, 16251, 16282, 16313, 16343, 16374, 16404, 16435, 16101,
          16129, 16160, 16190, 16221, 16251, 16282, 16313, 16343, 16374,
          16404, 16435
        ), class = "Date"
      ), measure = c(
        "cash_lvl", "cash_lvl",
        "cash_lvl", "cash_lvl", "cash_lvl", "cash_lvl", "cash_lvl", "cash_lvl",
        "cash_lvl", "cash_lvl", "cash_lvl", "cash_lvl", "tot_eq_lvl",
        "tot_eq_lvl", "tot_eq_lvl", "tot_eq_lvl", "tot_eq_lvl", "tot_eq_lvl",
        "tot_eq_lvl", "tot_eq_lvl", "tot_eq_lvl", "tot_eq_lvl", "tot_eq_lvl",
        "tot_eq_lvl"
      ), value = c(
        42845610.9859923, 42845610.9859923,
        42845610.9859923, 43947947.8113193, 43947947.8113193, 43947947.8113193,
        54130448.068727, 54130448.068727, 54130448.068727, 58733268.7486493,
        58733268.7486493, 58733268.7486493, 109715000, 109715000, 109715000,
        84928000, 84928000, 84928000, 94569000, 94569000, 94569000, 96630000,
        96630000, 96630000
      )
    ), row.names = c(NA,-24L), class = c("tbl_df",
                                         "tbl", "data.frame"), .Names = c("date", "measure", "value")
  )

dat.list <- split(dat, f = dat$measure)

highlight <- c('cash_lvl')

dat.plot.list <- lapply(seq_along(dat.list), function(d, n, f, i) {

  if(n[[i]] %in% f) {
    bckgrnd <- '#FFE3E3'
  } else {
    bckgrnd <- '#FFFFFF'
  }

  plot_ly(d[[i]], x = date, y = value) %>%
    layout(plot_bgcolor = bckgrnd)

}, d = dat.list, n = names(dat.list), f = highlight)

dat.plot.list[[1]]

的输出

enter image description here

但是,子图的输出仅显示白色背景

do.call(subplot, append(dat.plot.list, list(nrows = 2, margin = c(.025, .025, .1, .1))))

enter image description here

1 个答案:

答案 0 :(得分:1)

如果您将此部分layout(plot_bgcolor = bckgrnd)更改为:layout(plot_bgcolor = '#ffe3e3'),您应该在子图中获得正确的颜色。

如果我像这样修改着色条件,它也有效:if(n[[i]] %in% dat$measure)

所以输出是:

enter image description here