Plotly:如何将变量分配给子图标题?

Pat*_*ler 5 python subplot plotly plotly-python

我想在几个子图上显示额外的数据,并决定在子图标题中这样做。

我已经弄清楚如何向子图添加标题,但无法在每个子图中包含变量。到目前为止的代码是:

fig = make_subplots(rows=3, cols=1, subplot_titles=("Share Price is: ", "RSI is: ", "Portfolio Return is: "))
Run Code Online (Sandbox Code Playgroud)

我想在每个子图标题的末尾添加变量。

如何才能做到这一点?

S3D*_*DEV 3

这段代码就能帮助您实现目标。本质上,只需使用字符串格式(如果在 Python 3.6+ 上,则使用 f 字符串)。

\n

请注意开头的变量声明,然后是元titles组中的 f 字符串替换。您会注意到,由于使用了字符串,因此子图标题可以包含货币值、百分比、小数值……任何适合目的的内容。这些甚至可以直接从数据集中的值填充。

\n

示例代码:

\n
from plotly.subplots import make_subplots\n\nshr = \'\xc2\xa325.10\'\nrsi = \'40%\'\nrtn = \'12\'\n\n# Use f-strings to format the subplot titles.\ntitles = (f\'Share Price is: {shr}\', \n          f\'RSI is: {rsi}\', \n          f\'Portfolio Return is: {rtn}\')\n\nfig = make_subplots(rows=3, \n                    cols=1, \n                    subplot_titles=titles)\n\nfig.add_trace({\'y\': [1, 2, 3, 4, 5], \'name\': \'Share Price\'}, row=1, col=1)\nfig.add_trace({\'y\': [5, 4, 2, 3, 1], \'name\': \'RSI\'}, row=2, col=1)\nfig.add_trace({\'y\': [1, 4, 2, 3, 5], \'name\': \'Return\'}, row=3, col=1)\n\nfig.show()\n
Run Code Online (Sandbox Code Playgroud)\n

输出:

\n

在此输入图像描述

\n