将 hoverlabel 重新定位在栏的中间,这样它就不会覆盖标题

Reposition the hoverlabel in the middle of the bar, so it won't cover the title

数据框:

df2 = data.frame(value = c(10,10,10,10,10),
                 key = c('ar', 'or', 'br', 'gt', 'ko'))

剧情代码:

df2 %>% 
  plot_ly(y = ~value,
          x = ~key, 
          type = 'bar',
          hoverinfo = 'text',
          hovertext = paste0('this is a pretty huge text',
                             '\nand I would like to set the correct',
                             '\nposition of the hoverlabel, so it',
                             "\nwon't cover the title.",
                             '\n\nAlso, I would like to position it in the',
                             '\nmiddle of the bar, if possible')) %>% 
  layout(title = list(text = "This is the Title I don't want to be covered",
                      y = 0.98))

基本上,我在悬停标签中有一个漂亮的 huge hoverinfo,但它是 covering the title。我想将它放在 middle of the yaxis 中,这样我就可以继续阅读标题和悬停信息。这里有什么提示吗?

这比我称之为 'proper' 方法的技巧更多...

我所做的是添加 transparent 标记,y 为零,但 x 与条形相同。在最后两步中,我制作了悬停模式 x unified 并隐藏了图例。我的悬停框现在位于栏的中间。

df2 = data.frame(value = c(10,10,10,10,10),
                 value2 = c(0, 0, 0, 0, 0), # <-  I added this
                 key = c('ar', 'or', 'br', 'gt', 'ko'))

df2 %>% 
  plot_ly(y = ~value,
          x = ~key, 
          type = 'bar',
          #hoverinfo = 'text',                                # not needed
          hovertext = paste0('this is a pretty huge text',
                             '\nand I would like to set the correct',
                             '\nposition of the hoverlabel, so it',
                             "\nwon't cover the title.",
                             '\n\nAlso, I would like to position it in the',
                             '\nmiddle of the bar, if possible'),
          hovertemplate = '%{hovertext}<extra></extra>') %>%  # extra = hide trace name
  add_markers(y = ~value2, x = ~key, color = I("transparent"), 
              hovertemplate = '<extra></extra>') %>%          # trace invisible
  layout(title = list(text = "This is the Title I don't want to be covered",
                      y = 0.98),
         # only need hoverlabel if you want original color scheme back
         hoverlabel = list(bgcolor = '#1f77b4',
                           font = list(color = "white")), 
         hovermode = "x unified",                     # move hover box to bar center             
         showlegend = F)                              # no need to see trace info

如果您对颜色感到好奇,这里是 plot_ly 默认颜色列表。 https://community.plotly.com/t/plotly-colours-list/11730/2