r - 使用 R 绘图下拉菜单选择变量并继续使用颜色变量作为跟踪

标签 r plotly r-plotly

我在 R 中向绘图中添加了一个变量选择器(遵循通常的方法,即隐藏图中不必要的痕迹)

library(plotly)

dat <- mtcars
dat$cyl <- factor(dat$cyl)
dat$car <- rownames(mtcars)

dat %>% 
    plot_ly(x = ~car, y = ~mpg,
            name='mpg', type='scatter', mode='markers') %>%
     add_trace(y = ~hp, name = 'hp', type='scatter', mode='markers') %>%
     add_trace(y = ~qsec, name = 'qsec', type='scatter', mode='markers') %>%
       layout(
          updatemenus = list(
            list(
                type = "list",
                label = 'Category',
                buttons = list(
          list(method = "restyle",
               args = list('visible', c(TRUE, FALSE, FALSE)),
               label = "mpg"),
          list(method = "restyle",
               args = list('visible', c(FALSE, TRUE, FALSE)),
               label = "hp"),
          list(method = "restyle",
               args = list('visible', c(FALSE, FALSE, TRUE)),
               label = "qsec")
        )
      )
    )
  )

enter image description here

代码完成了这项工作,但它覆盖了组/颜色变量作为跟踪选择器的标准使用,因为我们已经设置了跟踪。

颜色/组变量的标准用法如下

plot_ly(group_by(dat,cyl), x = ~car, y = ~mpg, color = ~cyl, type='scatter', mode='markers')

注意:我使用 group_by() 因为 group = ... 已弃用。

enter image description here

是否可以将下拉菜单添加为变量选择器,并且仍然能够使用颜色/组变量来隐藏和显示所选变量的数据?

我尝试添加color= ~cyl,但是,正如你可以想象的,它不起作用。

提前致谢!!

最佳答案

试试这个。首先,我将数据集转换为长格式,以便变量成为一个变量 name 的类别,值在 value 中。其次,我将 name 映射到符号上,并将 cyl 映射到颜色上。第三。我通过将 cyl 映射到 add_trace 内的名称来调整图例标签,以便仅 cyl 显示在图例中。

library(plotly)

dat <- mtcars
dat$cyl <- factor(dat$cyl)
dat$car <- rownames(mtcars)

dat %>% 
  tidyr::pivot_longer(c(mpg, hp, qsec)) %>% 
  plot_ly(x = ~car, y = ~value, color = ~cyl, symbol = ~name) %>%
  add_trace(type='scatter', mode='markers', name = ~cyl) %>% 
  layout(
    updatemenus = list(
      list(
        type = "list",
        label = 'Category',
        buttons = list(
          list(method = "restyle",
               args = list('visible', c(TRUE, FALSE, FALSE)),
               label = "hp"),
          list(method = "restyle",
               args = list('visible', c(FALSE, TRUE, FALSE)),
               label = "mpg"),
          list(method = "restyle",
               args = list('visible', c(FALSE, FALSE, TRUE)),
               label = "qsec")
        )
      )
    )
  )

enter image description here

关于r - 使用 R 绘图下拉菜单选择变量并继续使用颜色变量作为跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61270022/

相关文章:

python-3.x - plotly python - 修复特定图例标签的颜色

r - 将动态数量的迹线添加到 Shiny 的图中

r - ggplot 分面图表重新排序未按预期工作

r - 具有不同列名称的 for 循环中的 left_join

python - 如果我尝试在 IPython 中绘制图表,则图表为空

R:双 Y 轴绘图?

javascript - R plotly : how to observe whether a trace is hidden or shown through legend clicks with multiple plots

r - 在 data.frame 中有效地定位分组常量列

r - 如何使用 header `postForm`

从 plotly 对象中删除悬停信息文本