如何让ggplotly堆叠柱状图每个条形悬停时显示对应单独总和
问题原因
原来的代码单独生成了年度总和向量d,但没有将每个年度的总和匹配到原数据的对应行,直接把整段向量传入text参数,导致每个条形悬停时都会加载所有年度的总和数据。
解决方案
直接在原始数据集里新增一列存储对应年度的总数值,再配置悬停文本即可,修正后的完整代码如下:
# 已加载对应包的情况下可跳过下面三行 library(dplyr) library(ggplot2) library(plotly) # 原始数据集读取后新增年度总数字段 df1 <- df1 %>% group_by(year_range) %>% mutate(year_total = sum(total)) %>% ungroup() Removestring(ggplotly( df1 %>% ggplot(aes(x = as.character(year_range), y = total, # 可自行调整拼接的悬停展示内容 text = paste("年度区间:", year_range, "\n所属行业:", Sector, "\n行业企业数:", total, "\n全年总企业数:", year_total))) + geom_col(aes(fill = Sector))+ theme_classic()+ theme(axis.line.y = element_blank(),axis.ticks = element_blank(),legend.position = "bottom")+ labs(x="", y="No.of total companies", fill="")+ theme(axis.title.y =element_text(size=8))+ scale_fill_manual(values=c("#1F7A3F","#0AAA4D","#70B821","#9BDFAF"))+ scale_y_continuous(labels = function(x) format(x, scientific = FALSE),expand = expansion(mult = c(0,.3)),breaks = integer_breaks()), tooltip = c("text"))%>% layout(legend = list(orientation = "h", x = 0.1, y = -0.2,font=list( family='Arial', size=10, color='black')),xaxis = x_labels,yaxis = y_labels)%>% config(displaylogo = FALSE,modeBarButtonsToRemove = list('sendDataToCloud', 'autoScale2d', 'resetScale2d', 'toggleSpikelines','hoverClosestCartesian', 'hoverCompareCartesian','zoom2d','pan2d','select2d','lasso2d','zoomIn2d','zoomOut2d')))
内容的提问来源于stack exchange,提问作者sayile firahs
相关产品推荐
相关产品推荐

