Plotly中hovertemplate无法识别传入的text文本向量问题咨询
问题原因
第一段代码中color参数映射的Country(s)变量与x轴取值完全一一对应,plotly会为每个国家单独生成1个仅包含1个数据点的bar trace。你将text参数放在color之前设置时,全局传入的长度为5的text向量不会被自动拆分分配到每个独立trace中,导致每个trace匹配不到对应的文本值,hovertemplate的%{text}就无法正常渲染。
而第二段可正常运行的代码中,color映射的Name变量每个取值对应多个数据点(每个季度对应多个周的统计值),每个trace包含多个数据点,text向量长度与trace内数据点数量匹配,因此可以正常识别。
解决方法
你可以选择以下任意一种方案修复问题:
- 调整参数顺序,将
text映射放在color参数之后,确保拆分后的每个trace都能正确继承对应的text值:
library(plotly) `Country(s)`<-c("United Kingdom", "Brazil", "United States Of America", "India", "Russian Federation") `Number of cases`<-c(1032990, 1264637, 5905072, 618694, 735681) lab<-c("1.0M", "1.3M", "5.9M", "618.7K", "735.7K") cm4d<-data.frame(`Country(s)`,`Number of cases`,lab, check.names = FALSE) fig1 <- plot_ly(cm4d, x = ~`Country(s)`, y = ~`Number of cases`, type = 'bar', colors = c("#60ab3d","#6bbabf","#c4d436","#3e5b84","#028c75"), color = ~`Country(s)`, text=~lab, hovertemplate = paste('%{x}', '<br>Number of cases: %{text}<br><extra></extra>')) fig1
- 避免拆分多trace,改用
marker.color参数直接指定每个柱子的颜色,不需要按国家拆分trace,text自然可以正常识别:
library(plotly) `Country(s)`<-c("United Kingdom", "Brazil", "United States Of America", "India", "Russian Federation") `Number of cases`<-c(1032990, 1264637, 5905072, 618694, 735681) lab<-c("1.0M", "1.3M", "5.9M", "618.7K", "735.7K") cm4d<-data.frame(`Country(s)`,`Number of cases`,lab, check.names = FALSE) fig1 <- plot_ly(cm4d, x = ~`Country(s)`, y = ~`Number of cases`, type = 'bar', text=~lab, marker = list(color = c("#60ab3d","#6bbabf","#c4d436","#3e5b84","#028c75")), hovertemplate = paste('%{x}', '<br>Number of cases: %{text}<br><extra></extra>')) fig1
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

