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

Plotly: How to assign a variable to subplot titles?

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

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

fig = make_subplots(rows=3, cols=1, subplot_titles=("Share Price is: ", "RSI is: ", "Portfolio Return is: "))

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

如何做到这一点?

在你的特殊情况下,我会在字典中组织不同的新元素:

infos = {'price':29,
         'RSI': 1.1,
         'return':1.1}

然后像这样 make_subplots() 中的字典子集:

fig = make_subplots(rows=3, cols=1, start_cell="top-left",
                    subplot_titles=("Share Price is: "+ str(infos['price']),
                                    "RSI is: " + str(infos['RSI']),
                                    "Portfolio Return is: " + str(infos['return'])))

为什么是字典?我经常发现自己处于这样一种情况,即我想在定义图形后对情节元素进行操作。通过这种方式,您的新元素也可以随时用于其他目的。

剧情:

完整代码:

import plotly.graph_objects as go
from plotly.subplots import make_subplots


infos = {'price':29,
         'RSI': 1.1,
         'return':1.1}

fig = make_subplots(rows=3, cols=1, start_cell="top-left",
                    subplot_titles=("Share Price is: "+ str(infos['price']),
                                    "RSI is: " + str(infos['RSI']),
                                    "Portfolio Return is: " + str(infos['return'])))

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
              row=1, col=1)

fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
              row=2, col=1)

fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]),
              row=3, col=1)

fig.show()
f2 = fig.full_figure_for_development(warn=False)

这一小段代码将带您到达那里。本质上,只需使用字符串格式(如果在 Python 3.6+ 上,则使用 f-strings)。

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

示例代码:

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()

输出: