Plotly滑块功能仅更新一个参数

问题描述 投票:0回答:1

我正在尝试使用注释和标题来构建热图。移动滑块时,此标题和注释应更新。我可以使用它,但是只能同时使用两个参数之一。索引为[1]的参数正在更新,而另一个参数不是

下面是我的代码段,该错误发生在循环步骤中:

from plotly.offline import init_notebook_mode, iplot
import plotly.graph_objs as go
import numpy as np

# initialize notebook for offline plotting 
init_notebook_mode()

# Set initial slider/title index
start_index = 0

# Build all traces with visible=False

timestep = 5

#df2 = np.random.rand(18,365)*70

data = [go.Heatmap(
            visible = False,
            x = ['P', 'C', 'S'],
            y = [11,10,9,8,7,6],
            z = df.iloc[:18,[step]].to_numpy().reshape(6,3),
            # z = df2[:,step].reshape(6,3),
            zmin = 0,
            zmax = 70)
        for step in np.arange(0, len(df2.transpose())-1, timestep)
       ]

# Make initial trace visible
data[start_index]['visible'] = True

# Build slider steps
steps = []
for i in range(len(data)):
    step = dict(
        # Update method allows us to update both trace and layout properties
        method = 'update', 
        args = [
            # Make the ith trace visible
            {'visible': [t == i for t in range(len(data))]},

            {'annotations' : [dict(
                    x = x,
                    y = y,
                    text = str(round(df.iloc[:18,[i]].to_numpy().reshape(6,3)[-y+11,x],1)),
                    # text = str(df2[:,i].reshape(6,3)[-y+11,x]),
                    showarrow = False)
                    for x in range(3) for y in range(6,12)]},

            {'title.text': str(df.columns[i*timestep])},]
    )
    steps.append(step)

# Build sliders
sliders = [go.layout.Slider(
    active = start_index,
    currentvalue = {"prefix": "Timestep: "},
    pad = {"t": 72},
    steps = steps
)]

layout = go.Layout(
    sliders=sliders,
    title={'text': str(df.columns[start_index])},
    yaxis =  dict(
             tickmode = 'array',
             tickvals = [11,10,9,8,7,6],
             ticktext = ['06','07','08','09','10','11']
        ),
    annotations = steps[start_index]['args'][1]['annotations']

)

fig = go.Figure(
    data=data,
    layout=layout)


iplot(fig)
python slider plotly updates heatmap
1个回答
0
投票

我发现了问题。显然,您需要在同一词典中指定'annotations''title.text,而不是单独的词典。因此,代码应更改为:

{'annotations' : [dict(
                    x = x,
                    y = y,
                    text = str(round(df.iloc[:18,[i]].to_numpy().reshape(6,3)[-y+11,x],1)),
                    # text = str(df2[:,i].reshape(6,3)[-y+11,x]),
                    showarrow = False)
                    for x in range(3) for y in range(6,12)],

 'title.text': str(df.columns[i*timestep])}
© www.soinside.com 2019 - 2024. All rights reserved.