r语言 - 如何在flexadashboard中传递输入$变量到renderPlotly



newData()是响应式语句根据用户输入动态生成的数据帧:

selectInput("year", "Year", c("2019", "2020", "2021"), selected = "2021")
selectInput("fruit", "Fruit", names(FruitSales$fname), selected = "Pineapple")

例如,对于2021年,newData()为:

fruit  x2021_sales
1    Pineapple 42
2       Orange 36
3       Carrot 56
4        Onion 82
5      Avocado 94
6     Mushroom 24
7        Apple 23
8       Banana 46
9        Mango 61
10  Strawberry 43

注意第二列的名称。它是通过连接"x"、输入$year和"_sales"生成的。

我想用plotly:labels = ~get(input$fruit), values = ~x20yy_sales绘制newData()的树状图。我试过几种方法。第一种方法是使用ggplot生成树图,然后用ggplot绘制树图。它没有工作,因为不知何故geom_treemap_text与plotly不兼容。第二个在下面:

renderPlotly({
treeplot <- plot_ly(NewData(),
labels = ~get(input$fruit),
parents = ~NA,
# values = ~x2021_sales, ## --> works
# values = paste0("x", input$year, "_sales"), ## --> doesn't work
# values = paste0("x", eval(as.name(input$year)), "_sales"), ## --> doesn't work
type = "treemap"
)
treeplot
})

没有values,仪表板工作,并给了我一个具有相同大小块的树状图。如果values = ~x2021_sales是硬编码的,它也可以工作。但是当我试图将input$year从输入侧栏传递到values时,没有任何效果。有人知道该怎么做吗?

编辑1:x = as.formula(paste0("~",input$x))建议版主返回错误,大意是"无效公式"。

编辑2:labels = ~get(input$fruit)的技巧是从这里借来的https://stackoverflow.com/questions/66337613/selective-y-variable-in-shiny-plotly-output和这里https://stackoverflow.com/questions/63543144/how-to-make-a-plotly-chart-of-variables-selected-by-a-user-in-shiny-or-flexdahsb。

这行得通:

input <- list(fruit = "Species",
year = "Length")
plotly::plot_ly(iris,
labels = ~get(input$fruit),
parents = ~NA,
# values = ~x2021_sales, ## --> works
values = ~get(paste0("Sepal.", input$year)), ## --> doesn't work
# values = paste0("x", eval(as.name(input$year)), "_sales"), ## --> doesn't work
type = "treemap"
)

所以请尝试:

renderPlotly({
treeplot <- plot_ly(NewData(),
labels = ~get(input$fruit),
parents = ~NA,
values = ~get(paste0("x", input$year, "_sales")), ## --> doesn't work
type = "treemap"
)
treeplot
})

相关内容

  • 没有找到相关文章

最新更新