使用plotly更新多个数据属性
我正在尝试更新通过 plotly
生成的图中的多个数据属性。
这是我基于此帖子的脚本:
library(plotly)
library(magrittr)
library(data.table)
X <- data.table(x = c(1, 2, 1, 2), y = c(1, 1, 2, 2), z = rep(c("a", "b"), each = 2))
gg <- ggplot() + geom_point(data = X, aes(x = x, y = y, color = z))
ggplotly(gg) %>%
layout(
updatemenus = list(
list(
buttons = list(
list(method = "restyle",
args = list(
list(x = list(X[z == "a", x])),
list(y = list(X[z == "a", y]))
),
label = "a"),
list(method = "restyle",
args = list(
list(x = list(X[z == "b", x])),
list(y = list(X[z == "b", y]))
),
label = "b")
)
)
)
)
但是,可以看出,更新菜单并未按预期工作。不确定问题是什么。
I am trying to update multiple data attributes in a figure generated via plotly
.
This is my script based on this post:
library(plotly)
library(magrittr)
library(data.table)
X <- data.table(x = c(1, 2, 1, 2), y = c(1, 1, 2, 2), z = rep(c("a", "b"), each = 2))
gg <- ggplot() + geom_point(data = X, aes(x = x, y = y, color = z))
ggplotly(gg) %>%
layout(
updatemenus = list(
list(
buttons = list(
list(method = "restyle",
args = list(
list(x = list(X[z == "a", x])),
list(y = list(X[z == "a", y]))
),
label = "a"),
list(method = "restyle",
args = list(
list(x = list(X[z == "b", x])),
list(y = list(X[z == "b", y]))
),
label = "b")
)
)
)
)
However, as can be seen, the update menu does not work as intended. Not sure what the problem is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
上述
args
参数中的列表过多。此外,当调用
restyle
而不指定跟踪编号时,您将重新设计所有跟踪。如果您想重新设计单个跟踪,您需要提供其跟踪索引:
我不知道你想达到什么目的。
如果您想在选择“a”时显示迹线“a”,在选择“b”时显示迹线“b”,则此过滤器方法是有问题的,因为它会从图中完全删除迹线(减少数据集),并且一旦迹线被选中,删除后您将无法再重新设计它的样式。
如果您只想切换跟踪可见性,则应使用
visible
参数,而不是修改数据:PS:
Plotly.restyle
期望跟踪计数开始从0开始(JS)和style()
来自 1 (R)使用 addTraces< /a>/deleteTraces 完成此处 将是另一种方法。但是,如果数据保持不变,我想切换可见性的计算强度较小。
There are too many lists in your above
args
parameter.Furthermore, when calling
restyle
without specifying the trace number you are restyling all traces.If you want to restyle a single trace you need to provide its trace index:
I'm not sure what you are trying to achive.
If you want to show trace "a" when "a" is selected and trace "b" when "b" is selected this filter approach is problematic, as it completly removes traces (reduces the dataset) from the plot and once the trace is removed you can no longer restyle it.
If you just want to toggle the trace visibility you should use the
visible
parameter instead of modifying the data:PS:
Plotly.restyle
expects the trace count starting from 0 (JS) andstyle()
from 1 (R)Using addTraces/deleteTraces as done here would be another approach. However, if the data stays the same I guess toggling the visibility is less computationally intensive.