繁体   English   中英

在 R Plotly 中按组使用 RGB 客户颜色

[英]Use RGB Customers Colors by Group in R Plotly

我有几个系列,我想用 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

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
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM