【问题标题】:Use RGB Customers Colors by Group in R Plotly在 R Plotly 中按组使用 RGB 客户颜色
【发布时间】:2020-04-08 11:43:51
【问题描述】:

我有几个系列,我想用 plotly R 制作动画。按照此处的示例 (https://plot.ly/r/cumulative-animations/) 进行操作后,我可以制作动画了。我想出了如何更改组的颜色,但是,我需要组的特定颜色(RGB 自定义颜色)。

我有两个问题:

  1. 如何将 RGB 颜色分配给 R Plotly 中的组...我在这里缺少什么?
  2. 有更简单的方法吗?我有几个“城市”,而不仅仅是两个,并且希望能够动态分配特定的颜色。我能够将颜色作为数据框中的一列拉入,并希望能够以这种方式分配它们...让它适用于常规颜色,但需要将它用于 RGB...
library(plotly)

# Helper function to create frames
accumulate_by <- function(dat, var) {
  var <- lazyeval::f_eval(var, dat)
  lvls <- plotly:::getLevels(var)
  dats <- lapply(seq_along(lvls), function(x) {
    cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
  })
  dplyr::bind_rows(dats)
}

# Pull in data and also create color columns
d <- 
  txhousing %>%
  filter(year > 2005, city %in% c("Abilene", "Bay Area")) %>%
  accumulate_by(~date) %>%
  mutate(regular_color = if_else(city == "Abilene", 'red', 'black'),
         RGB_color = if_else(city == "Abilene", 'rgb(229,18,18)', 'rgb(13,9,9)'))

# color vectors
reg_color_vector <- 
  d %>%
  arrange(city) %>%
  select(regular_color) %>%
  distinct() %>%
  pull()
RGB_color_vector <- 
  d %>%
  arrange(city) %>%
  select(RGB_color) %>%
  distinct() %>%
  pull()

p <- d %>%
  plot_ly(
    x = ~date, 
    y = ~median,
    split = ~city,
    frame = ~frame, 
    type = 'scatter',
    mode = 'lines', 
    line = list(simplyfy = F),
    color = ~city,
    # colors = c('red', 'black')
    colors = c('rgb(229, 18, 18)', 'rgb(13, 9, 9)')
    # colors = reg_color_vector
    # colors = RGB_color_vector
  ) %>% 
  layout(
    xaxis = list(
      title = "Date",
      zeroline = F
    ),
    yaxis = list(
      title = "Median",
      zeroline = F
    )
  ) %>% 
  animation_opts(
    frame = 100, 
    transition = 0, 
    redraw = FALSE
  ) %>%
  animation_slider(
    hide = T
    ) %>%
  animation_button(
    x = 1, xanchor = "right", y = 0, yanchor = "bottom"
  )

p

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    rgb() 是一个函数,它输出你想要的颜色的十六进制值。这就是您需要存储的内容。删除' 应该没问题。并且您需要将maxColorValue = 255 添加到rgb() 函数中。

    d <- 
      txhousing %>%
      filter(year > 2005, city %in% c("Abilene", "Bay Area")) %>%
      accumulate_by(~date) %>%
      mutate(regular_color = if_else(city == "Abilene", 'red', 'black'),
             RGB_color = if_else(city == "Abilene", 
                                 rgb(229, 18, 18, maxColorValue = 255), 
                                 rgb(13, 9, 9, maxColorValue = 255)))
    

    您可以使用plot_ly 而非RGB_color_vector 来定义颜色。

    plot_ly(
      x = ~date, 
      y = ~median,
      split = ~city,
      frame = ~frame, 
      type = 'scatter',
      mode = 'lines', 
      line = list(simplyfy = F),
      color = ~city,
      colors = RGB_color_vector
    )
    

    【讨论】:

    • 完美。我没有尝试过引用,但省略了max 声明让我失望。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 2015-11-24
    • 2021-01-02
    • 2018-09-01
    • 2019-03-20
    • 2016-06-06
    • 1970-01-01
    相关资源
    最近更新 更多