Plotly:如何根据系列中的差异自定义标记?

Plotly: How to customize markers depending on differences in a series?

我有这种线+标记图。我正在使用 plotly go scatter 创建此图表。我想要的是,减去列表中的两个数字,如果差值大于 5,则标记为黑色。 如图所示 y=[7,9,14,16,17,10,10] 在这种情况下,14-9=差异为 5,10-17=abs 5

def setcolor(x):
         if x[1]-x[0]>=5
         return 'black' 
         else:
         return 'orange'
fig = go.Scatter(y=df['data'], 
                        mode='markers+lines', name='data',
                        marker = dict(color=list(map(SetColor, df['data']))),
                        line=dict(color='rgb(200,200,200)'
                           ))

但它不起作用。我使用了这种方法。

我会在你的数据框中设置你自己的系列中的绝对差异,然后使用带有 mode=markers 的额外跟踪来说明满足你的标准的点。与对相同标记使用注释相比,主要好处是您现在可以使用 plotlys 交互性轻松隐藏或显示突出显示的标记。下面的代码片段将生成此图:

完整代码:
import numpy as np
import pandas as pd
import plotly.graph_objects as go

# data
df = pd.DataFrame({'No':[5,7,12,11,5,10,9,15,16,13],
                    'Name':['nab', 'cab', 'mun', 'city',
                            'coun', 'nwa', 'kra', 'ihr', 'nor', 'del']})


#df.index = list('abcdefg')
diffs=df['No'].to_list()

# find differences in list
diff=[abs(j-i) for i, j in zip(diffs[:-1], diffs[1:])]
D=[np.nan]
D=D+diff

# check if difference is greater than 5
D = [x if x >= 5 else np.nan for x in D]
df['diff']=D
df['ix']=df.index
df2=df.dropna()

# plotly setup
fig=go.Figure(go.Scatter(y=df['No'], x=df['Name'],
                         mode='lines+markers'))
fig.add_traces(go.Scatter(y=df2['No'], x=df2['Name'],
                          mode='markers', marker=dict(color='black', size=14)))

fig.show()