R plotly : Custom hover text does not appear when only one stacked bar

标签 r hover plotly

我一直在使用关于自定义悬停文本 ( https://plot.ly/r/text-and-annotations/ ) 的示例来更改我正在处理的条形图中的悬停文本。如果我的条形图仅包含一个堆叠条,则不会显示新的悬停文本。示例(在最后一个缺少 hoverinfo 的 plotly 中):

library(plotly)
year <- c(2015,2015,2016,2016)
type <- c('A','B','A','B')
perc <- c(10,90,20,80)

data <- data.frame(year,type,perc)

# Plot all the data ... default hoverinfo shown
plot_ly(data,x=~year,y=~perc,color=~type) %>% 
  add_bars()%>% 
  layout(barmode = "stack")

# Plot all the data ... custom hoverinfo shown
plot_ly(data,x=~year,y=~perc,color=~type,
  text = ~paste('Type',type,': ',perc,'%'),hoverinfo = 'text') %>% 
  add_bars()%>% 
  layout(barmode = "stack")

# Plot part of the data ... default hoverinfo shown
plot_ly(data[data$year == 2015,],x=~year,y=~perc,color=~type) %>% 
  add_bars()%>% 
  layout(barmode = "stack")

# Plot part of the data ... custom hoverinfo does not appear!
plot_ly(data[data$year == 2015,],x=~year,y=~perc,color=~type,
  text = ~paste('Type',type,': ',perc,'%'),hoverinfo = 'text') %>% 
  add_bars()%>% 
  layout(barmode = "stack")

使用 R 版本 3.3.2 和 plotly 版本 4.5.6。

最佳答案

得到一些帮助,解决方案是将文本定义为列表。

plot_ly(data[data$year == 2015,],x=~year,y=~perc,color=~type,
  text = ~list(paste('Type',type,': ',perc,'%')),hoverinfo = 'text') %>% 
  add_bars()%>% 
  layout(barmode = "stack")

只要我知道只有一个柱并且 ~type 的顺序在整个数据集中是相同的,这就有效。如果我将类型更改为

type <- c('A','B','B','A')

然后运行

data <- data.frame(year,type,perc)
plot_ly(data[data$year == 2016,],x=~year,y=~perc,color=~type,
      text = ~list(paste(year,'Type',type,': ',perc,'%')),hoverinfo = 'text') %>% 
  add_bars()%>% 
  layout(barmode = "stack") 

我没有得到 hoverinfo 的正确顺序。所以这不是完美的解决方案。

关于R plotly : Custom hover text does not appear when only one stacked bar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40850415/

相关文章:

r - 使用 ggplot2 根据人口普查数据绘制 map

r - 如何通过sf找到一个点属于哪个多边形

css - 用悬停的CSS改变不透明度SVG

javascript - 在 jQuery 函数中声明多个 div 选择器

javascript - 悬停效果与 jQuery 影响容器 div

javascript - 使用plotly.js 对单个数据进行多个Y 轴图例

java - 运行使用 Maven 构建的 jar 会导致 "java.lang.NoClassDefFoundError: org/rosuda/JRI/Rengine"错误

python - 如何使用 Plotly-Dash 调整 slider 和选择器的范围

python - 一页上的多个 plotly plots 没有子图

从 R 中的 data.table 有条件地删除行