firmo23
firmo23

Reputation: 8404

Text argument causes error in plotly bar chart

Im trying to create plotly bar chart with the code below but I get error of different sizes of my columns. The text seems to have different size but why.

month_year<-structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 
                          13L, 14L, NA), .Label = c("2020-Mar", "2020-Apr", "2020-May", 
                                                    "2020-Jun", "2020-Jul", "2020-Aug", "2020-Sep", "2020-Oct", "2020-Nov", 
                                                    "2020-Dec", "2021-Jan", "2021-Feb", "2021-Mar", "2021-Apr"), class = "factor")
  First<-c(862, 19117, 121572, 588123, 882046, 1401836, 1065476, 813419, 
           834485, 916300, 1264637, 1369098, 2025535, 474664, 267236)
  lab<-c("862", "19,117", "121,572", "588,123", "882,046", "1,401,836", 
         "1,065,476", "813,419", "834,485", "916,300", "1,264,637", "1,369,098", 
         "2,025,535", "474,664", "267,236")
  re<-data.frame(month_year,First,lab)

  
      p <- plot_ly() %>% 
        add_bars(re, x = ~month_year, y = ~First, name = "Brazil", 
                 marker = list(color = "#3E5B84"), offsetgroup = 1,
                 text = ~ paste("<b>Country:</b>", "Brazil", "<br><b>Date:</b>",~month_year , "<br><b>Cases:</b>", ~lab),
                 hovertemplate = paste('%{text}<extra></extra>')) %>%
        layout(
          showlegend=T,
          xaxis = list(title = "Date"),
          yaxis = list(title = "Brazil"),
          margin = list(b = 100),
          barmode = 'group',
          legend=list(title=list(text='<b> Country </b>'))
        )
      
      p%>%
        config(modeBarButtonsToRemove = c('toImage',"zoom2d","toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian","drawline","autoScale2d" ,"resetScale2d","zoomIn2d","zoomOut2d","pan2d",'select2d','lasso2d'))%>%
        config(displaylogo = FALSE)  
      

Upvotes: 0

Views: 205

Answers (1)

kwes
kwes

Reputation: 433

There's two things happening. First, re is being parsed as a plotly object instead of a dataframe because the data argument to add_bars is optional. The plot works because it references the external vectors, not the supplied df. Also, you don't need formula syntax (~) inside the function supplied to the text argument, that's what is causing the error.

p <- plot_ly() %>% 
    add_bars(data=re, x = ~month_year, y = ~First, name = "Brazil", 
                     marker = list(color = "#3E5B84"), offsetgroup = 1,
                     text = ~paste("<b>Country:</b>","Brazil","<br><b>Date:</b>",month_year,"<br><b>Cases:</b>",lab),
                     hovertemplate = paste('%{text}<extra></extra>')) %>%
    layout(
        showlegend=T,
        xaxis = list(title = "Date"),
        yaxis = list(title = "Brazil"),
        margin = list(b = 100),
        barmode = 'group',
        legend=list(title=list(text='<b> Country </b>'))
    )

Upvotes: 2

Related Questions