使用plot_ly函数出现非预期标签动画问题求助
问题解决:Plotly柱状图动画时文本异常显示
问题现象
使用plot_ly绘制柱状图时,仅希望文本在悬停(hover)时显示,但点击播放动画后,部分柱状图标签从图表左上角移动到对应柱子上,还有部分在柱子内产生动画效果。
使用环境
- RStudio 2022.07.2 Build 576
- R版本3.6.1
- plotly 4.10.1
原代码
fig <- df %>% plot_ly(x = ~x, y = ~value, color = ~variable, frame = ~variable, text = ~paste("Tran: ", x, '<br>Disp:', value, ' m'), hoverinfo = "text", type = 'bar') fig <- fig %>% animation_opts( frame =6000, transition = 4000, redraw = FALSE ) fig <- fig %>% animation_slider( currentvalue = list(prefix = "Years ", font = list(color="red")) ) fig
解决方案
问题根源在于plotly的bar trace中,text参数默认会同时作为柱子标签和hover文本使用,动画切换时这些标签会出现异常移动效果。只需在plot_ly()中添加textposition = 'none',即可禁用柱子上的标签显示,仅保留hover时的文本展示。
修改后的代码:
fig <- df %>% plot_ly(x = ~x, y = ~value, color = ~variable, frame = ~variable, text = ~paste("Tran: ", x, '<br>Disp:', value, ' m'), hoverinfo = "text", type = 'bar', textposition = 'none') # 新增这一行 fig <- fig %>% animation_opts( frame =6000, transition = 4000, redraw = FALSE ) fig <- fig %>% animation_slider( currentvalue = list(prefix = "Years ", font = list(color="red")) ) fig
说明
设置textposition = 'none'后,plotly不会渲染柱子上的文本标签,仅在鼠标悬停时展示text参数定义的内容,动画切换时也不会出现标签移动的异常效果。
内容的提问来源于stack exchange,提问作者masspern
相关产品推荐
相关产品推荐

