在 Plotly Indicator python 中显示相对和绝对差异

Show both relative and absolute difference in Plotly Indicator python

我正在尝试使用 plotly.graph_objs.Indicator 来显示输出。

go.Indicator(mode = "number+delta", value = 200,
             number = {'font': {'size': 30}},
             title = {'text': 'HEAD', 'font':{'size':20, 'color':'green'}},
             domain = {'x': [0, 1], 'y': [0, 1]},
             delta = {'reference':300, 'relative':False})

这里如果我传递relative=True,相对差异将显示为例如。 30%.

如果我传递 relative=False,例如,将显示绝对差异。 -20

有什么方法可以同时获得绝对和相对差异。

看来相对和绝对的变化是通过go.Indicator方法内部计算出来的(意思是不能自定义delta符号旁边显示的文字),得选择要显示的相对或绝对变化之间。

最简单的解决方案是添加文本注释。但是,独立文本不是 graph_object,而是呈现在图形上。这意味着文本可以与图中的其他图形 object 重叠。

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Indicator(
    mode = "number+delta", 
    value = 200,
    number = {'font': {'size': 30}},
    title = {'text': 'HEAD', 'font':{'size':20, 'color':'green'}},
    domain = {'x': [0, 1], 'y': [0, 1]},
    delta = {'reference':300, 'relative':False})
)

fig.add_annotation(x=0.5, y=0.4, text="-30%", font=dict(color="red"), showarrow=False)

fig.show()

该图在相当大的浏览器中看起来还不错 window:

但是当你调整浏览器大小时 window,文本注释可以覆盖 go.Indicator object 这很丑陋:

一个更好但有难度的解决方案是添加三个不同的 go.Indicator objects 作为跟踪:前两个 go.Indicator objects 将显示相对和绝对变化但我们将把数字的字体颜色设置为背景颜色,这样它们就不可见了。然后第三个 go.Indicator object 添加数字 200 和标题 HEAD 而不显示增量。最后一件事是相应地设置每个 go.Indicator object 的域,以便它们在您调整浏览器大小时不会重叠 window.

您可以调整每个轨迹的域,使您更接近您正在寻找的结果。

fig = go.Figure()

# the first two traces are just the delta with the value set to the background color
fig.add_trace(go.Indicator(
    mode = "number+delta", 
    value = 200,
    number = {'font': {'size': 30, 'color':'rgb(255,255,255,0)'}},
    domain = {'x': [0, 0.8], 'y': [0, 0.8]},
    delta = {'reference':300, 'relative':False})
)

fig.add_trace(go.Indicator(
    mode = "number+delta", 
    value = 200,
    number = {'font': {'size': 30, 'color':'rgb(255,255,255,0)'}},
    domain = {'x': [0.2, 1], 'y': [0, 0.8]},
    delta = {'reference':300, 'relative':True})
)

## this adds the title and value
fig.add_trace(go.Indicator(
    mode = "number", 
    value = 200,
    number = {'font': {'size': 30}},
    title = {'text': 'HEAD', 'font':{'size':20, 'color':'green'}},
    domain = {'x': [0, 1], 'y': [0, 1]})
)

fig.show()

这是该图在大型浏览器中的样子window:

当您调整浏览器 window 大小时,go.Indicator 痕迹仍然清晰: