Search code examples
rhoverplotlyscatter-plotr-plotly

R plotly hover label text alignment


I'm adding custom hover text for scatterplot points in a plotly graph in R. It appears to be aligning the text left, center, or right depending on whether the text box is shown to the right, center, or the left of the plot points, respectively. I'd prefer if the text was always aligned left regardless of the positioning of the box. I've been able to style the font, e.g. setting the color and size, but haven't been able to change the text alignment.

Here's an MRE. I've removed the legend so the points on the far right are forced to have their hover boxes appear to the left of the point.

plot_ly(iris,
        x = ~Sepal.Length,
        y = ~Sepal.Width,
        type = 'scatter',
        mode = 'markers',
        hoverinfo = 'text',
        hoverlabel = list(font = list(color = 'white')),
        text = ~paste0('Some rather long text',
                       '\nSepal.Length: ', Sepal.Length,
                       '\nSepal.Width: ', Sepal.Width)) %>%
  layout(showlegend = FALSE)

enter image description here


Solution

  • This is now controllable via the layout.hoverlabel.align attribute: https://plot.ly/r/reference/#layout-hoverlabel-align

    For example:

    ggplotly(p1) %>% layout(hoverlabel = list(align = "left"))