在 plotly 中创建总和的分组条形图
Create a grouped bar chart of sums in plotly
我有下面的数据框:
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
。
请检查以下内容:
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
我有下面的数据框:
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
。
请检查以下内容:
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