11

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

Brian Stamper
  • 2,143
  • 1
  • 18
  • 41
  • I think I've narrowed this down to how the hover text SVG is built by plotly, here: https://github.com/plotly/plotly.js/blob/master/src/lib/svg_text_utils.js#L123 I can use CSS to force `text-anchor: start` on the class `.nums`, but then the pre-computed x position is not correct. – Brian Stamper Apr 26 '18 at 15:25
  • 1
    Found an issue report on this here: https://github.com/plotly/plotly.js/issues/260 – Brian Stamper Apr 26 '18 at 15:29
  • It is already left-aligned for me with your code. – SeGa Sep 13 '19 at 11:17
  • The issue I linked to has been fixed and closed, so you may have a more up-to-date version where this is no longer an issue. – Brian Stamper Sep 13 '19 at 15:09

1 Answers1

6

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")) 
nico
  • 50,859
  • 17
  • 87
  • 112
nicolaskruchten
  • 26,384
  • 8
  • 83
  • 101