我在R中使用plotly
时遇到了一些麻烦。我正在创建rmarkdown,并利用updatemenus
和transforms
功能添加了下拉菜单。我做了一些虚拟数据以突出说明我遇到的问题。
我希望能够以离散的方式控制颜色。每个组中有3个人,当您更改组时,我希望他们具有相同的颜色集。因此,在这种情况下,a的颜色= d的颜色; b = e,c = f。
实际上,我有更多的组,所以当我设置该图时,组中我的颜色几乎没有变化,而且看起来不专业。
下面是示例代码,有关如何执行此操作的任何想法都很棒。否则,我将不得不尝试使用ggplot和ggplotly进行重写,发现它们看起来不够精致,并且我会尽可能地使用plotly函数。
library(plotly)
library(RColorBrewer)
# make data. Assign first set a-c to group 1, d-f to group 2
set.seed(1)
df <- data.frame(individual = sample(letters[1:6], 100, replace = TRUE),
x = runif(100), stringsAsFactors = FALSE)
groups <- c("g1", "g2")
df$group[match(df$individual, letters) <= 3] <- groups[1]
df$group[match(df$individual, letters) > 3] <- groups[2]
df$y <- df$x*(match(df$individual, letters))
df <- df[order(df$individual),]
# can see data is split ok
table(df$group, df$individual)
# build up interactive element, the filter to the two groups
button_list <- lapply(1:length(groups), function(x){
list(method = "restyle",
args = list("transforms[0].value", groups[x]),
label = groups[x])
})
type_list <- list(
type = 'dropdown',
active = 0,
xanchor = 'center',
yanchor = "top",
pad = list('r'= 0, 't'= 10, 'b' = 10),
x = 0.5,
y = 1.27,
buttons = button_list
)
# make plot, color based on the individual in the group
plot_ly(df, x = ~x, y = ~y, mode = "lines+markers",
color = ~ individual,
colors = brewer.pal(3, "Set1"),
hoverinfo = "text", text = ~paste(individual),
transforms = list(
list(
type = 'filter',
target = ~group,
operation = '=',
value = df$group[1]
))
) %>%
layout(updatemenus = list(
type_list
))
欢呼
答案 0 :(得分:1)
又快又脏:用“允许的”颜色填充颜色
colors = rep( brewer.pal(3, "Set1"), 2)