python - Plotly:如何将变量分配给子情节标题?
问题描述
我想在几个子图上显示额外的数据,并决定在子图标题中这样做。
我已经想出了如何为子图添加标题,但无法在每个子图中包含一个变量。到目前为止的代码是:
fig = make_subplots(rows=3, cols=1, subplot_titles=("Share Price is: ", "RSI is: ", "Portfolio Return is: "))
我想在每个子图标题的末尾添加变量。
如何才能做到这一点?
解决方案
这段代码将带您到达那里。本质上,只需使用字符串格式(或在 Python 3.6+ 上使用 f 字符串)。
注意开头的变量声明,然后是titles
元组中的 f 字符串替换。您会注意到,由于使用了字符串,因此子图标题可以包含货币值、百分比、十进制值......任何适合目的的东西。这些甚至可以直接从数据集中的值中填充。
示例代码:
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()
输出: