2017-04-20 18 views
0

아래 코드를 사용하여 그림과 같이 누적 막 대형 차트가 있습니다. 누적 막대 차트 상단에 계산 된 값을 표시하는 방법

enter image description here

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 

나는 각 막대의 상단에있는 순 추천 점수를 보여주고 싶어요. 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

당신은 x 값이 날짜는 당신의 layoutannotation의를 추가 할 수는 y 값은 스택 값은 텍스트, 예를 들어를 Net Promoter Score입니다

enter image description here

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) 

또는이 특정 예를 들어 사용하여 코드의 마지막 두 줄 대체 :

annotations <- list() 
for (row in rownames(myDF)) { 
    annotations[[as.integer(row)]] = list(x = as.character(myDF[row,]$Group), 
           y = sum(myDF[row,][-1]), 
           text = ((myDF[row,][[3]] - myDF[row,][[4]])/sum(myDF[row,][-1])) * 100, 
           yanchor='bottom', 
           showarrow = FALSE) 

} 
p <- layout(p, xaxis = x, yaxis = y, barmode = 'stack', legend = list(orientation = 'h'), showlegend=T, 
      annotations = annotations) 

p 

enter image description here