You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flexdashboard中如何将input$year传入renderPlotly的treemap values参数

问题:Plotly treemap动态传递values参数失败

背景信息

输入控件代码

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

newData()数据结构(以2021年为例)

数据框第二列名称由x + input$year + _sales拼接而成:

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

尝试的方法与遇到的问题

  1. ggplot转ggplotly方案:用ggplot生成treemap后转成ggplotly,但geom_treemap_text与plotly不兼容,无法正常显示文本。

  2. 直接使用plotly treemap方案:硬编码values = ~x2021_sales可以正常生成对应大小的treemap,但尝试动态传递年份参数时全部失败:

    renderPlotly({
        treeplot <- plot_ly(NewData(),
                 labels = ~get(input$fruit),
                 parents = ~NA,
                 # values = ~x2021_sales, ## 可行
                 # values = paste0("x", input$year, "_sales"), ## 不可行
                 # values = paste0("x", eval(as.name(input$year)), "_sales"), ## 不可行
                 type = "treemap"
                    )
      treeplot
    })
    

    注:不设置values时会生成等块大小的treemap。

  3. 尝试过版主建议的x = as.formula(paste0("~",input$x)),但返回"invalid formula"错误。

解决方案

可以通过以下两种方式实现动态传递values参数:

方法1:使用get()函数动态获取列

直接在公式中用get()拼接目标列名:

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

方法2:提前构造公式对象

先动态生成合法的公式,再传入values参数:

renderPlotly({
    values_formula <- as.formula(paste0("~", paste0("x", input$year, "_sales")))
    treeplot <- plot_ly(NewData(),
             labels = ~get(input$fruit),
             parents = ~NA,
             values = values_formula,
             type = "treemap"
                )
  treeplot
})

两种方法都能根据选中的年份动态获取对应销售额列,生成大小匹配的treemap。

内容的提问来源于stack exchange,提问作者tcollar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 18:05:18