分组数据框与 plotl_ly() 组合时会导致错误 [英] Grouping dataframe causes error when it is combined with plotl_ly()

查看:55
本文介绍了分组数据框与 plotl_ly() 组合时会导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过创建一个名为 customdata 的列表来显示在我的悬停文本 Name,lab Week 中,我将其传递给 plot_ly().问题是我收到错误 Size 2: Columns x, y, color, hovertemplate, .plotlyGroupIndex, and 2 more.* 大小 6:列自定义数据.[34mℹ[39m 仅回收大小为 1 的值. 但我不明白为什么大小有所不同.我的意思是我在添加 lab 后得到了一个新数据集,但由于上述问题而无法使其工作

Im trying to display in my hovertext Name,lab and Week by creating a list named customdata which I pass to plot_ly(). The problem is that Im getting the error Size 2: Columns x, y, color, hovertemplate, .plotlyGroupIndex, and 2 more. * Size 6: Column customdata. [34mℹ[39m Only values of size one are recycled. but I do not understand why there is a difference in size. I mean that I get a new dataset after adding lab and cannot make it work due to issue above

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

推荐答案

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

You just need to format your customdata with the vector of character instead

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

这是输出

这篇关于分组数据框与 plotl_ly() 组合时会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆