【发布时间】:2020-04-08 11:43:51
【问题描述】:
我有几个系列,我想用 plotly R 制作动画。按照此处的示例 (https://plot.ly/r/cumulative-animations/) 进行操作后,我可以制作动画了。我想出了如何更改组的颜色,但是,我需要组的特定颜色(RGB 自定义颜色)。
我有两个问题:
- 如何将 RGB 颜色分配给 R Plotly 中的组...我在这里缺少什么?
- 有更简单的方法吗?我有几个“城市”,而不仅仅是两个,并且希望能够动态分配特定的颜色。我能够将颜色作为数据框中的一列拉入,并希望能够以这种方式分配它们...让它适用于常规颜色,但需要将它用于 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
【问题讨论】: