firmo23
firmo23

Reputation: 8454

Grouping dataframe causes error when it is combined with plotl_ly()

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

Upvotes: 1

Views: 120

Answers (1)

Sinh Nguyen
Sinh Nguyen

Reputation: 4497

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

Here is the output enter image description here

Upvotes: 3

Related Questions