how do i assign a variable to subplot titles?

This little bit of code will get you there. Essentially, just use string formatting (or f-strings if on Python 3.6+).

Note the variable declarations at the beginning, then the f-string substitution in the titles tuple. As you’ll notice, since strings are being used, the subplot titles can contain monetary values, percentages, decimal values … whatever suites the purpose. These can even be populated directly from values in your dataset.

Sample code:

from plotly.subplots import make_subplots

shr = '£25.10'
rsi = '40%'
rtn = '12'

# Use f-strings to format the subplot titles.
titles = (f'Share Price is: {shr}', 
          f'RSI is: {rsi}', 
          f'Portfolio Return is: {rtn}')

fig = make_subplots(rows=3, 
                    cols=1, 
                    subplot_titles=titles)

fig.add_trace({'y': [1, 2, 3, 4, 5], 'name': 'Share Price'}, row=1, col=1)
fig.add_trace({'y': [5, 4, 2, 3, 1], 'name': 'RSI'}, row=2, col=1)
fig.add_trace({'y': [1, 4, 2, 3, 5], 'name': 'Return'}, row=3, col=1)

fig.show()

Output:

enter image description here

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top