[英]Use RGB Customers Colors by Group in R Plotly
我有几个系列,我想用 plotly R 制作动画。在按照这里的示例( https://plot.ly/r/cumulative-animations/ )之后,我有动画工作。 我想出了如何更改组的颜色,但是,我需要组的特定颜色(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.