数据框:
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 轴的中间,这样我就可以继续阅读标题和悬停信息。这里有什么提示吗?
最佳答案
这更像是一个技巧,而不是我所谓的“正确”方法......
我所做的是添加透明标记,其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
关于将悬停标签重新放置在栏的中间,这样它就不会覆盖标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72077327/