【问题标题】:Grouping dataframe causes error when it is combined with plotl_ly()与 plotl_ly() 结合使用分组数据框会导致错误
【发布时间】:2021-05-09 16:51:06
【问题描述】:

我试图通过创建一个名为customdata 的列表来显示在我的hovertext Name,lab and Week 中,我将其传递给plot_ly()。问题是我收到错误Size 2: Columns x, y, color, hovertemplate, .plotlyGroupIndex, and 2 more. * Size 6: Column customdata. [34mℹ[39m Only values of size one are recycled. 但我不明白为什么大小会有所不同。我的意思是我在添加lab 后获得了一个新数据集,但由于上述问题而无法使其工作

library(plotly)
library(dplyr)

full_data<-data.frame("Name"=c("Q1","Q2","Q3","Q1","Q2","Q3"),"Values"=c(245645,866556,26440,65046,641131,463265),
                      "Week"=c("a","b","c","d","e","f"))
desc <- full_data %>% 
  group_by(Name,Week) %>% 
  summarise(values = sum(Values)) %>%
  mutate(lab = scales::label_number_si(accuracy = 0.1)(values))


      plot_ly(desc,
              x = ~Week, 
              y = ~values,
              #text = ~values,
              color = ~Name,
              colors = c("#60ab3d","#6bbabf","#c4d436","#3e5b84","#028c75","red"),
              customdata = mapply(function(x,y) list(x,y), desc$lab, desc$Name, SIMPLIFY = FALSE)) %>%
        add_trace(
          type = 'scatter',
          mode = 'lines+markers',
          hovertemplate = paste(
            "%{x}",
            "%{customdata[0]}", 
            "%{customdata[1]}", 
            "<extra></extra>",
            sep = "\n"),
          hoveron = 'points')

【问题讨论】:

    标签: r dplyr plotly


    【解决方案1】:

    您只需要使用字符向量来格式化您的自定义数据

    plot_ly(desc,
        x = ~Week, 
        y = ~values,
        #text = ~values,
        color = ~Name,
        # I saw that you have only 3 Name in the sample data so I reduce
        # this to only 3 color instead of 7 like you have originally
        colors = c("#60ab3d","#6bbabf", "#c4d436"),
        # combine the lab & Name from desc data using paste0
        customdata = paste0(desc$lab, "\n", desc$Name)) %>%
        add_trace(
          type = 'scatter',
          mode = 'lines+markers',
          hovertemplate = paste(
            "%{x}",
            "%{customdata}",
            sep = "\n"),
          hoveron = 'points')
    

    这是输出

    【讨论】:

      猜你喜欢
      • 2021-04-11
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      • 2021-03-19
      相关资源
      最近更新 更多