将悬停标签重新放置在栏的中间,这样它就不会覆盖标题

标签 r plotly r-plotly

数据框:

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))

基本上,我的悬停标签中有一个相当巨大的悬停信息,但它覆盖了标题。我想将其放置在 y 轴的中间,这样我就可以继续阅读标题和悬停信息。这里有什么提示吗?

enter image description here

最佳答案

这更像是一个技巧,而不是我所谓的“正确”方法......

我所做的是添加透明标记,其y为零,但x与条形相同。在最后两步中,我将悬停模式设为x统一并隐藏了图例。我的悬停框现在位于条形图的中间。

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

enter image description here

enter image description here

关于将悬停标签重新放置在栏的中间,这样它就不会覆盖标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72077327/

相关文章:

r - 在 R Plotly 中使用曲面椭圆绘制 Ellipse3d

r - 在堆积条形图中悬停时 plotly 给出不正确的文本

r - 图片作为 Shiny 仪表板的背景

r - 制作一个重复的字母数字列表

r - 如何在 Shiny 应用程序的 selectModUI 中更新传单 map ?

python - 在Python中读取Pandas数据框中的 float 时出现问题

angular - 当鼠标悬停在 Plotly.js 上时,Plotly.js 显示的不是跟踪的全名

r - 在 R 中创建一个函数

html - 将 pandas 数据框导出到 HTML 中的可排序表格

R:双 Y 轴绘图?