Функция Plotly Slider обновляет только один аргумент - PullRequest
0 голосов
/ 01 апреля 2020

Я пытаюсь построить тепловую карту с аннотациями и заголовком. Этот заголовок и аннотации должны обновляться при перемещении ползунка. Я понимаю, что это работает, но только для одного из двух аргументов одновременно. Аргумент, который находится в index [1], обновляется, но другой не

Ниже приведен фрагмент моего кода, и ошибка возникает в шаге для l oop:

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)

1 Ответ

0 голосов
/ 01 апреля 2020

Я нашел проблему. Очевидно, вам нужно указать '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])}
...