以下是示例数据的代码:
library(tidyverse)
library(plotly)
df <- data_frame(
date = Sys.Date() - seq(0, 99, by = 0.2)[2:101],
cut = rep(c("Ideal", "Premium", "Very Good", "Good", "Fair"), 20),
y = sample_n(diamonds, size = 100)$depth,
z = sample_n(diamonds, size = 100)$price
)
以下是情节的代码:
plot_ly(df, x = ~date, y = ~y, color = ~cut,
type = "scatter", mode = "lines") %>%
layout(
title = "Drop down menus - Change y",
xaxis = list(title = "x"),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = list(
list(method = "restyle",
args = list("y", list(~y)),
label = "Show Y"),
list(method = "restyle",
args = list("y", list(~z)),
label = "Show Z")))
))
我会执行代码,渲染绘图,并且它看起来像我想要的方式:通过时间对分类变量的事物计数。目标是让下拉列表替换另一个y
变量,在这种情况下为z
。
基于文档中的一些玩具示例以及此处的几个答案,我认为这应该有效。相反,看起来所有的值都奇怪地崩溃成一行。似乎没有办法在不重新运行代码的情况下将绘图恢复到原始状态。
任何人都知道如何让它正常工作?
这是我的plotly
版本:
packageVersion("plotly")
[1] ‘4.5.6.9000’
答案 0 :(得分:0)
你可以通过
让它工作plot_ly(df, x = ~date, color = ~cut)
add_trace
:add_trace(y = ~z, type = 'scatter', mode = 'lines', visible=F
)但隐藏第二条跟踪restyle
隐藏/显示每一组:args = list("visible", append(rep(list(TRUE), 5), rep(list(FALSE), 5)))
在Ubuntu 16和Windows 10上使用R-Studio上的4.5.6版本为我工作。
library('tidyverse')
library('plotly')
df <- data_frame(
date = Sys.Date() - seq(0, 99, by = 0.2)[2:101],
cut = rep(c("Ideal", "Premium", "Very Good", "Good", "Fair"), 20),
y = sample_n(diamonds, size = 100)$depth,
z = sample_n(diamonds, size = 100)$price
)
p <- plot_ly(df, x = ~date, color = ~cut) %>%
add_trace(y = ~y, type = 'scatter', mode = 'lines', visible=T) %>%
add_trace(y = ~z, type = 'scatter', mode = 'lines', visible=F)
p <- p %>% layout(
updatemenus = list(
list(
buttons = list(
list(method = "restyle",
args = list("visible", append(rep(list(TRUE), 5), rep(list(FALSE), 5))),
label = "Show Y"),
list(method = "restyle",
args = list("visible", append(rep(list(FALSE), 5), rep(list(TRUE), 5))),
label = "Show Z")))
))