【问题标题】:Create a grouped bar chart of sums in plotly在 plotly 中创建总和的分组条形图
【发布时间】:2021-05-10 20:40:36
【问题描述】:

我有下面的数据框:

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)

我想使用相对悬停模板创建一个按案例和性别分组的条形图,例如:

我的代码:

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

我的问题是我无法显示每个年龄段的总和,并且每个条形都像被切成小块,我无法在悬停文本中显示 gender

【问题讨论】:

    标签: r plotly r-plotly


    【解决方案1】:

    请检查以下内容:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-01-04
      • 2021-08-10
      • 1970-01-01
      • 2021-01-17
      • 2021-01-18
      • 2021-11-05
      • 2023-02-26
      • 1970-01-01
      相关资源
      最近更新 更多