如何在R中堆积条形图的顶部显示总值

问题描述

我有一个数据框,其中用R绘制了堆积的条形图

myDF <- data.frame("group" = c("A","B","C","A","C"),"date" = c("25-May","25-May","01-Jun","01-Jun"),"hours" = c(42,48,51,32,25,48),stringsAsFactors = FALSE)

p <- plot_ly(myDF,x = myDF$date,y = myDF$group,type = 'bar',name = myDF$group,text = myDF$Hours,color = myDF$group,colors = brewer.pal(length(unique(myDF$group)),"Paired"))%>%
  layout(barmode = 'stack',hoverlabel = list(bgcolor= 'white'),bargap = 0.5) %>%
  layout(xaxis = list(categoryorder = 'array',categoryarray = myDF$date),showlegend = F)

我有另一个数据框,其中我本周的总时数如下:

totalHours <- data.frame(
                          "date" = c("25-May","hours" = c(141,105))

我试图像这样在栏的顶部显示堆栈总数

annotations <- list()
for (i in 1:length(totalHours$hours)) {
  annotations[[i]] <- list(x = totalHours$date[[i]],text = totalHours$hours[[i]],yanchor='bottom',showarrow = FALSE)
}

在图的布局中添加了注释

p <- p %>% layout(annotations = annotations)

enter image description here

我将标签放在顶部,而不是顶部。我不清楚代码中哪里有遗漏。谁能为此提供解决方案?

提前谢谢!

解决方法

您可以尝试一下。标签位置有问题:

library(plotly)
library(RColorBrewer)
#Data
myDF <- data.frame("group" = c("A","B","C","A","C"),"date" = c("25-May","25-May","01-Jun","01-Jun"),"hours" = c(42,48,51,32,25,48),stringsAsFactors = FALSE)
#Plot
p <- plot_ly(myDF,x = myDF$date,y = myDF$group,type = 'bar',name = myDF$group,text = myDF$Hours,color = myDF$group,colors = brewer.pal(length(unique(myDF$group)),"Paired"))%>%
  layout(barmode = 'stack',hoverlabel = list(bgcolor= 'white'),bargap = 0.5) %>%
  layout(xaxis = list(categoryorder = 'array',categoryarray = myDF$date),showlegend = F)
#Data2
totalHours <- data.frame(
  "date" = c("25-May","hours" = c(141,105),stringsAsFactors = F)

#Create global coordinate
labs <- myDF %>% group_by(group) %>% mutate(Tot = sum(hours),Prop=hours/Tot) %>% 
  ungroup() %>% summarise(Val=sum(Prop))
#Annotate
annotations <- list()
for (i in 1:length(totalHours$hours)) {
  annotations[[i]] <- list(x = totalHours$date[[i]],y = labs$Val,text = totalHours$hours[[i]],yanchor='bottom',showarrow = FALSE)
}
#Final plot
p <- p %>% layout(annotations = annotations)

输出:

enter image description here

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...