r - 用于选择 x、y 和颜色(绘图)的下拉菜单

标签 r plotly r-plotly

我正在尝试创建一个具有可选 x、y 和颜色变量的绘图,部分基于 this previous question 。 x 和 y 变量选择似乎有效,但是当选择新的 x 和 y 变量时,点颜色会丢失。

此外,我尝试使用类似的策略来选择点颜色,但不幸的是这似乎不起作用。

另一种选择是在之前链接的问题中使用“设置可见”策略。

示例:

library(plotly)
library(pcaMethods)

pca <- pcaMethods::pca(mtcars, nPcs=3)

df <- as.data.frame(pca@scores)

colors1 <- sample(c("red", "green", "blue"), nrow(df), replace=TRUE)
colors2 <- sample(c("red", "green", "blue"), nrow(df), replace=TRUE)

p <- plotly::plot_ly(df, x = ~PC1, y = ~PC2, type = "scatter",
    color = sample(c("red", "green", "blue"), nrow(df), replace=TRUE),
    mode = "markers") 

p <-  plotly::layout(
    p,
    title = "Dropdown PCA plot",
    updatemenus = list(
        list(
            y = 0.7,
            buttons = list(
                list(method = "restyle",
                   args = list(
                    "x", list(df$PC1)
                    ),
                   label = "PC1"),
                list(method = "restyle",
                   args = list(
                    "x", list(df$PC2)
                    ),
                   label = "PC2"),
                list(method = "restyle",
                   args = list(
                    "x", list(df$PC3)
                    ),
                   label = "PC3")
                )
            ),
        list(
            y = 0.5,
            buttons = list(
                list(method = "restyle",
                   args = list(
                    "y", list(df$PC1)
                    ),
                   label = "PC1"),
                list(method = "restyle",
                   args = list(
                    "y", list(df$PC2)
                    ),
                   label = "PC2"),
                list(method = "restyle",
                   args = list(
                    "y", list(df$PC3)
                    ),
                   label = "PC3")
                )
            )
        )
    )

htmlwidgets::saveWidget(p, "test.html", selfcontained=FALSE)

最佳答案

目前这在 R API 中是不可能的,因为从变量到绘图输出的映射是在 R 端完成的,而不是由plotly.js 完成的。

以下链接对此进行了解释:https://github.com/ropensci/plotly/issues/803

此功能可以使用plotly.js 和 HTML 来完成。必须将 select 元素添加到 HTML 页面,并添加事件监听器以在更新时调用 Plotly.newPlot()

可以在此处查看示例实现:https://github.com/Alanocallaghan/plotlyutils/blob/master/inst/htmlwidgets/lib/selectable_scatter_plot/selectable_scatter_plot.js

关于r - 用于选择 x、y 和颜色(绘图)的下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40719220/

相关文章:

r - 如何将向量与其自身卷积 n 次

python - 在绘图散点图中按下按钮时更新轴

python - Plotly:如何组织下拉菜单?

r - 绘制多个更新菜单

r - 如何关闭在 Plotly 中显示我的所有数据的工具提示?

r - 如何在R中的数据帧的一列中对具有相同值的行进行配对

r - 使用 'write.table' 时出现额外字符问题

r - 创建词组而不是R中的单个词的 "word"云

python - plotly - 在 Plot.JS 中使用 graph_objects.Figure 轨迹