New line in text in Plotly
Asked Answered
S

2

11

From other questions about this (in R though) I understood that you should be able to use HTML in (some?) text elements in Plotly. However, if I try this to get a new line in a text I add to my plot it will simply display the html tag as text and not 'parse' it. I also tried adding '\n' but that just gets ignored.

The code for the trace I'm using;

trace = go.Scattergl(
    x=[0.5],
    y=[4.5],
    text=['A: {} <br> B: {}\nC: {}\nD: {}'.format(a, b, c, d)],
    mode='text'
    )

Other than that I'm using the 'standard' code to generate the graph;

traces = [trace]
layout = {
    'xaxis':{
        'range':[0,7],
        'showgrid': False,
    },
    'yaxis':{
        'range':[0,7],
        'showgrid': False,
    },
}
fig = dict(data=traces, layout=layout)
plot(fig)

How can I add a new line in this situation?

Study answered 20/3, 2019 at 14:24 Comment(0)
W
15

I found that using <br> works inside hovertext, but not in the text placed directly on the figure. That was good enough for my use case, maybe it will help you too? Here's an example similar to what you provided in your question that demonstrates the difference. The string used in the hover text and the annotation is the same, but the break is only registered in the hovertext.

import plotly.graph_objects as go

a = 1
b = 2
c = 3
d = 4

trace = go.Scattergl(
    x=[0.5],
    y=[4.5],
    text=f'A: {a} <br> B: {b}\nC: {c}\nD: {d}',
    hoverinfo='text',
    mode='markers+text'
    )

traces = [trace]
layout = {
    'xaxis':{
        'range':[0,7],
        'showgrid': False,
    },
    'yaxis':{
        'range':[0,7],
        'showgrid': False,
    },
}
fig = go.Figure(data=traces, layout=layout)
fig.show(renderer='browser')
Wrack answered 27/11, 2019 at 17:32 Comment(1)
<br> now works for the text column for meBurtonburty
P
0

For plotly Express: scatter3d

Here I first reduce the text to a maximum number of n_chars. Then I break the text into newlines after a period. The separator in the join-function to use is <br>:

text_list_reduced: list[str] = ['<br>'.join(text[:n_chars].split('.')) for text in text_list]
fig = px.scatter_3d(x=df_data.x, y=df_data.y, z=df_data.z, color=df_data.label, text=text_list_reduced)
Paleozoic answered 12/7 at 12:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.