简体   繁体   English

Plotly R-交互式滤镜和按组离散的颜色

[英]Plotly R - interactive filter & discrete colour by group

I'm having some troubles with plotly in R. I am creating an rmarkdown, and am making use of the updatemenus & transforms feature to add a drop down. 我在R中使用plotly遇到了一些麻烦。我正在创建一个rmarkdown,并利用updatemenustransforms功能添加一个下拉列表。 I've made some dummy data to highlight the problem that I have. 我做了一些虚拟数据以突出说明我遇到的问题。

I want to be able to control the colours in a discrete way. 我希望能够以离散的方式控制颜色。 I have 3 individuals in each group, and I want them to have the same set of colours when you change group. 每个组中有3个人,当您更改组时,我希望他们具有相同的颜色集。 so colour of a = colour of d in this case; 因此,在这种情况下,a的颜色= d的颜色; b=e, c=f. b = e,c = f。

In reality I have a lot more groups, so when I set this plot up, my colours within a group barely vary, and it looks unprofessional. 实际上,我有更多的组,所以当我设置该图时,组中的颜色几乎没有变化,而且看起来不专业。

Sample code is below, any ideas how to do this would be great. 下面是示例代码,有关如何执行此操作的任何想法都很棒。 Otherwise I'll have to try rewritting with ggplot and ggplotly which I find look less polished, and I try to use the plotly functions where I can. 否则,我将不得不尝试使用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
                 ))

Cheers 干杯

快速又脏:用“允许的”颜色填充颜色

colors = rep( brewer.pal(3, "Set1"), 2)

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

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