Search code examples
rplotlyr-plotly

Create a grouped bar chart of sums in plotly


I have the dataframe below :

agegroup<-c("0-4","0-4","5-15","5-15")
gender<-c("Male","Female","Male","Female")
week<-c("a","b","c","d")
cases<-c(20,40,35,67)
df<-data.frame(agegroup,gender,week,cases)

and I want to create a grouped bar chart by cases and gender with the relative hovertemplate like:

enter image description here

my code :

fig <- plot_ly(df, x = ~agegroup, y = ~cases, type = 'bar', name = 'Male',hovertemplate = paste('%{x}', '<br>cases: %{y}<br><extra></extra>'), marker = list(color = '#6bbabf'))
fig <- fig %>% add_trace(y = ~cases, name = 'Female',hovertemplate = paste('%{x}', '<br>cases: %{y}<br><extra></extra>'), marker = list(color = '#60ab3d'))
fig <- fig %>% layout(barmode = 'group')
fig
fig

my issues are that I cannot display the total sum per age group and every bar is like is cut into pieces and I cannot display the gender in my hovertext.


Solution

  • Please check the following:

    library(plotly)
    library(data.table)
    
    agegroup <- c("0-4", "0-4", "5-15", "5-15")
    gender <- c("Male", "Female", "Male", "Female")
    week <- c("a", "b", "c", "d")
    cases <- c(20, 40, 35, 67)
    df <- data.frame(agegroup, gender, week, cases)
    setDT(df)
    df[, agegroupsum := sum(cases), by = agegroup]
    # setDF(df)
    
    fig <- plot_ly(
        data = df,
        x = ~ agegroup,
        y = ~ cases,
        type = 'bar',
        color = ~ gender,
        colors = c('#6bbabf', '#60ab3d'),
        text = ~ paste("<b>Gender:</b>", gender, "<br><b>Age:</b>", agegroup, "<br><b>Cases:</b>", cases, "<br><b>Total cases in age group:</b>", agegroupsum),
        hovertemplate = paste('%{text}<extra></extra>')
      ) %>% layout(barmode = 'group')
    
    fig
    

    result