【问题标题】:Plotly: How to assign a variable to subplot titles?Plotly:如何将变量分配给子情节标题?
【发布时间】:2021-02-19 11:13:00
【问题描述】:

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

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

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

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

如何做到这一点?

【问题讨论】:

  • 这是一个简单的字符串格式化问题。看看 f-strings(如果在 Py3.6+ 上);否则使用字符串格式。

标签: python plotly subplot plotly-python


【解决方案1】:

这段代码将带您到达那里。本质上,只需使用字符串格式(或在 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()

输出:

【讨论】:

  • 带 f 弦的不错!
【解决方案2】:

在您的特定情况下,我只会在 dict 中组织不同的新元素:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多