如何将input$variable传递到flexadashboard中的renderPlotly [重复]

ssm49v7z  于 2022-12-25  发布在  其他
关注(0)|答案(1)|浏览(112)
    • 此问题在此处已有答案**:

How to make a plotly chart of variables selected by a user in shiny or flexdahsboard?(1个答案)
Using R Shiny with plotly to make a scatterplot(2个答案)
Selective y variable in shiny plotly output(1个答案)
4天前关闭。
newData()是由基于用户输入的React性语句动态生成的 Dataframe :

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"、input $year和"_sales"生成的。
我想用以下函数绘制newData()的树形图:labels = ~get(input$fruit), values = ~x20yy_sales。我尝试了几种方法。第一种是使用ggplot生成一个树图,然后ggplotly它。它没有工作,因为不知何故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, Jmeter 板可以正常工作,并给我一个具有相同大小块的树形图。如果values = ~x2021_sales是硬编码的,它也可以正常工作。但是当我试图将input$year从输入侧边栏传递到values时,什么都不起作用。有人知道该怎么做吗?
编辑1:主持人建议的x = as.formula(paste0("~",input$x))返回错误,大意是"无效公式"。
Edit 2: The trick of labels = ~get(input$fruit) was borrowed from here https://stackoverflow.com/questions/66337613/selective-y-variable-in-shiny-plotly-output and here https://stackoverflow.com/questions/63543144/how-to-make-a-plotly-chart-of-variables-selected-by-a-user-in-shiny-or-flexdahsb.

nkoocmlb

nkoocmlb1#

这是可行的:

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
})

相关问题