我在 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")
)
)
)
)
代码完成了这项工作,但它覆盖了组/颜色变量作为跟踪选择器的标准使用,因为我们已经设置了跟踪。
颜色/组变量的标准用法如下
plot_ly(group_by(dat,cyl), x = ~car, y = ~mpg, color = ~cyl, type='scatter', mode='markers')
注意:我使用 group_by()
因为 group = ...
已弃用。
是否可以将下拉菜单添加为变量选择器,并且仍然能够使用颜色/组变量来隐藏和显示所选变量的数据?
我尝试添加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")
)
)
)
)
关于r - 使用 R 绘图下拉菜单选择变量并继续使用颜色变量作为跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61270022/