首页 > 解决方案 > R Plotly - add_trace 按组对值求和

问题描述

尝试构建一个按图分组的条形图,该条形图通过对列进行分组来添加一条对值求和的线。

这是一个例子:

if (interactive()) {
  library(plotly)
  
  year <- c("2020", "2020", "2021", "2021", "2022", "2022", "2023", "2023", "2024", "2024", "2025", "2025")
  foodType <- c("Vegetable", "Fruit", "Vegetable", "Fruit", "Vegetable", "Fruit", "Vegetable", "Fruit", "Vegetable", "Fruit", "Vegetable", "Fruit")
  foodQty <- c(10, 10, 11, 17, 21, 23, 3, 4, 16, 2, 7, 43)
  
  data <- data.frame(year, foodType, foodQty)

  
  ui <- fluidPage(
    plotlyOutput("foodPlot")
  )
  
  server <- function(input, output, session) {
    output$foodPlot <- renderPlotly({
      plot_ly(data, x = ~year, y = ~foodQty, type = 'bar', color = ~foodType,
              hoverinfo = 'text',
              hovertext = ~paste0(foodType, ' ', foodQty)) %>%
        add_trace(x = ~year, y = ~foodQty,
                  type = 'scatter', mode = 'lines', name = 'Total Qty',
                  line = list(color = 'red'),
                  hoverinfo = "text",
                  hovertext = ~paste(foodQty),
                  transforms = list(list(type = 'aggregate', groups = ~year,
                                         aggregations = list(list(target = 'y', func = 'sum', enabled = T))))) %>%
        layout(xaxis = list(title = "", tickangle = -90), yaxis = list(title = ""),
               barmode = 'group') %>%
        config(displaylogo = FALSE, collaborate = FALSE,
               modeBarButtonsToRemove =
                 list("sendDataToCloud","zoom2d","pan2d","select2d","lasso2d",
                      "zoomIn2d","zoomOut2d","autoScale2d","hoverClosestCartesian",
                      "hoverCompareCartesian"))
    })
  }
  shinyApp(ui, server)
}

我的目标是有一条红色的Total Qty线,总和为year. 所以在 2020 年它将是 20,在 2021 年它将是 28,等等。在这个例子中,我尝试使用该transforms属性,但它没有像我想象的那样工作。

我也尝试替换 to 中的xandyadd_trace

x = ~aggregate(data$foodQty, by=list(year=data$year), FUN=sum)$year,
y = ~aggregate(data$foodQty, by=list(year=data$year), FUN=sum)$x,

仍然没有运气。谢谢你的帮助!

标签: rshinyplotly

解决方案


您可以使用inherit = FALSE来避免从plot_ly()to传递属性add_trace并通过以下方式创建新数据集aggregate- 请检查以下内容:

library(shiny)
library(plotly)

year <- c("2020", "2020", "2021", "2021", "2022", "2022", "2023", "2023", "2024", "2024", "2025", "2025")
foodType <- c("Vegetable", "Fruit", "Vegetable", "Fruit", "Vegetable", "Fruit", "Vegetable", "Fruit", "Vegetable", "Fruit", "Vegetable", "Fruit")
foodQty <- c(10, 10, 11, 17, 21, 23, 3, 4, 16, 2, 7, 43)

data <- data.frame(year, foodType, foodQty)

ui <- fluidPage(
  plotlyOutput("foodPlot")
)

server <- function(input, output, session) {
  output$foodPlot <- renderPlotly({
    plot_ly(data, x = ~year, y = ~foodQty, type = 'bar', color = ~foodType,
            hoverinfo = 'text',
            hovertext = ~paste0(foodType, ' ', foodQty)) %>%
      add_trace(data = aggregate(foodQty ~ year, data = data, sum), x = ~year, y = ~foodQty,
                type = 'scatter', mode = 'lines', name = 'Total Qty',
                line = list(color = 'red'),
                hoverinfo = "text",
                hovertext = ~paste(foodQty), inherit = FALSE) %>%
      layout(xaxis = list(title = "", tickangle = -90), yaxis = list(title = ""),
             barmode = 'group') %>%
      config(displaylogo = FALSE, collaborate = FALSE,
             modeBarButtonsToRemove =
               list("sendDataToCloud","zoom2d","pan2d","select2d","lasso2d",
                    "zoomIn2d","zoomOut2d","autoScale2d","hoverClosestCartesian",
                    "hoverCompareCartesian"))
  })
}
shinyApp(ui, server)

结果


推荐阅读