如何在r中的堆积条形图上显示计算值

时间:2017-04-20 19:17:13

标签: r plotly stacked-chart

使用下面的代码,我有一个堆积的条形图,如图所示。

myDF <- structure(list(Group = structure(1:3, .Label = c("2017-04-02", 
"2017-04-09", "2017-04-16"), class = "factor"), Passive = c(4, 
1, 0), Promoter = c(12, 1, 4), Detractors = c(0, 0, 0)), .Names = c("Group", 
"Passive", "Promoter", "Detractors"), row.names = c(NA, -3L), class = "data.frame")


x <- list(
  title = ""
)
y <- list(
  title = "Count"
)

p <- plot_ly(myDF, x = ~Group)

if ("Detractors" %in% colnames(myDF[-1])){
  p <- add_trace(p, y = ~`Detractors`, name = 'Detractors', type = 'bar',
                 marker = list(color = '#D52728')) #red
}
if ("Passive" %in% colnames(myDF[-1])){
  p <- add_trace(p, y = ~`Passive`, name = 'Passive', type = 'bar', 
                 marker = list(color = '#1F78B4')) #orange
}
if ("Promoter" %in% colnames(myDF[-1])){
  p <- add_trace(p, y = ~`Promoter`, name = 'Promoter', type = 'bar', 
                 marker = list(color = '#2BA02D')) #green
}
p <- layout(p, xaxis = x, yaxis = y, barmode = 'stack', legend = list(orientation = 'h'), showlegend=T)

p

enter image description here

我想在每个栏上显示净推荐人得分。我用来计算NPS的公式是: (Number of Promoters — Number of Detractors) / (Number of Respondents) x 100。 所以对于第一个栏,它将是((12 - 0)/16) * 100 = 75。我想在第一个栏顶部显示NPS: 75。类似地,对于第二个和第三个条形,顶部的数字将分别为(1-0)/2*100 = 50(4-0)/4*100 = 100。我将在未来几周获得更多数据,因此将来每周都会有一个数据库。有没有办法在条形图上显示这个计算值?

1 个答案:

答案 0 :(得分:3)

您可以将annotation添加到layout,其中x值是您的日期,y值是堆叠值,文字是{{1}例如

enter image description here

Net Promoter Score

或者对于此特定示例,使用以下代码替换代码的最后两行:

df = data.frame(x = c('A', 'B', 'C', 'D'),
                y = c(1,3,2,4),
                calculated_values = c(20,30,10,50)
)
annotations <- list()
for (i in 1:length(df$calculated_values)) {
  annotations[[i]] <- list(x = df$x[[i]],
                           y = df$y[[i]],
                           text = df$calculated_values[[i]],
                           yanchor='bottom',
                           showarrow = FALSE)

}
plot_ly(df,
        x = ~x, 
        y = ~y, 
        type = 'bar') %>% 
  layout(annotations = annotations)

enter image description here