Search code examples
plotlyplotly.js

Multiple data labels (or multi-line labels) above bars in Plotly


Is it possible to add multiple text labels, or equivalently, multi-line text labels in Plotly using the official JSON API?

I tried entering labels as arrays, strings with <br/>, &#x10;, \n, etc. to no avail. My fallback option is to render it with some delimiter and then use D3 to break the into multiple lines.

The blue text below is what Id like, the grey text is what I;m getting.

enter image description here


Solution

  • Almost!

    In python you need to use </br></br> but should work for you too :)

    Reproducible example:

    (Made it for chart title, plots titles, legends, xlabels... But should work for everything else.)

    from plotly.subplots import make_subplots
    import plotly.graph_objects as go
    
    fig = make_subplots(rows=2, subplot_titles=("Plot</br></br>Number 1", "Plot</br></br>Number 2"))
    
    fig.add_scatter(y=[2, 1, 3], row=1, col=1, name='TEST</br></br>HEHE') 
    fig.add_scatter(y=[1, 3, 2], row=2, col=1, name='TEST2</br></br>HEHE')
    
    fig.update_xaxes(tickmode='array',
                    tickvals=[0,1,2,3],
                    ticktext=['AAA</br></br>AAA','BBB</br></br>BBB', 'CCC</br></br>CCC'])
    
    fig.update_layout(title_text='Your title</br></br>here', showlegend=True)
    

    Output:

    (Don't know why my uploaded pic looks more like a thumbnail than an image. Click on it to zoom in.)

    enter image description here