Search code examples
rplotlyr-plotly

How to wrap text on dumbbell chart


I need to wrap text on my dumbbell chart. Dataset is here https://www.file.io/download/ODUcXav56m9c

enter image description here

How do I make the graph show the entire statements? My code is below:

overallp$statement <- factor(overallp$statement, levels = 
overallp$statement[order(overallp$prior)])
library(plotly)
fig <- plot_ly(overallp, color = I("gray36"))
fig <- fig %>% add_segments(x = ~prior, xend = ~current, y = ~statement,  size = I(4),yend = 
~statement, showlegend = FALSE, size = I(6))
fig <- fig %>% add_markers(x = ~prior, y = ~statement, size = I(50), name = "Prior Year", 
color = I("dodgerblue3"))
fig <- fig %>% add_markers(x = ~current, y = ~statement, size = I(50), name = "Current 
Year", color = I("gold"))
fig <- fig %>% layout(

xaxis = list(title = "Mean", showgrid = TRUE),
yaxis = list(title = "", showgrid = TRUE),
margin = list(l = 100))

fig <- fig %>% layout( xaxis = list(title = 'Mean')) %>% add_text(x = ~current, y = 
~statement,text = ~current, texttemplate="%{text}%", textposition = "top right", color = 
I("gold"), showlegend = FALSE)
fig <- fig %>% add_text(x = ~prior, y = ~statement,text = ~prior, texttemplate="%{text}%", 
textposition = "top right",color = I("dodgerblue3"), showlegend = FALSE)

fig

Solution

  • One option is to use str_wrap from stringr to wrap the text.

    overallp$statement <- stringr::str_wrap(overallp$statement, 55)
    

    enter image description here

    You can play around with the width parameter according to your choice.