Plotly:如何使用 updatemenus 更新一个特定的跟踪?

Plotly: How to update one specific trace using updatemenus?(Plotly:如何使用 updatemenus 更新一个特定的跟踪?)
本文介绍了Plotly:如何使用 updatemenus 更新一个特定的跟踪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 Plotly 的后续问题:

代码:

# 导入导入 plotly.graph_objs将熊猫导入为 pd将 numpy 导入为 np# 数据df1 = pd.DataFrame({'index': ['1','2','3'], 'A': [10,10,12], 'B': [11,11,11]})df2 = pd.DataFrame({'index': ['1','2','3'], 'A': [10,10,10], 'B': [11,11,12]})# 绘制图形设置fig=go.Figure()fig.add_trace(go.Scatter(x=df1['index'], y=df1['A'], mode='lines'))fig.add_trace(go.Scatter(x=df1['index'], y=df1['B'], mode='lines'))f=fig.to_dict()#fig.show()按钮=列表([dict(args=[{'y':[df1['A'],df1['B']]}],标签=df1",方法=重新设计";),dict(args=[{'y':[df2['A'], df2['B']]}],标签=df2",方法=重新设计";)])fig.update_layout(更新菜单=[go.layout.Updatemenu(按钮=按钮,方向=向下",pad={r":10,t":10},showactive=真,x=-0.25,xanchor=左",y=1,yanchor=顶部";),])图.show()

在上面的代码段中,我使用按钮和 dict(args=[{'y':[df2['A'], df2['B']]}].这会为图中指定的 both 轨迹分配新值,如下所示 fig-to_dict:

'data': [{'mode': 'lines','x': 数组(['1', '2', '3'], dtype=object),'y': 数组([10, 10, 12], dtype=int64),'类型':'分散'},{'模式':'线','x': 数组(['1', '2', '3'], dtype=object),'y': 数组([11, 11, 11], dtype=int64),类型":分散"}]

由于我已将列表 [df2['A'], df2['B']] 分配给 'y',因此我知道我打算在上面的代码片段中更新 'y' 的两个实例.但是在按钮和更新菜单的上下文中,有没有办法我可以指定 which 'y' 来更新(换句话说:什么特定的迹线或线).如果我只分配一个引用(在本例中为数组或 pandas 数据框),则两条迹线将显示相同的值.所以改变以下部分:

 args=[{'y':[df2['A'], df2['B']]}]

...用这个:

args=[{'y':[df2['A']]}]

... 将在单击 df2 时生成以下图:

我真的很想保持所有未指定的 'y' 和痕迹不变.

感谢您的任何建议!

解决方案

在您为每个 button 传递给 args 的列表中,您可以在dict 指示要更新的跟踪.例如,以下将仅更新第一个跟踪(即 index=0 处的跟踪)

buttons=list([dict(args=[{'y':[df1['A'],df1['B']]}, [0]], # 注意这里的`, [0]`!标签="df1",方法=重新样式"),dict(args=[{'y':[df2['A'], df2['B']]}, [0], # 注意这里的`, [0]`!标签="df2",方法=重新样式")])

This is a follow-up question to Plotly: Plotly: How do the buttons for the update menus really work?

Consider the following plotly figure produced by the code snippet below:

Plot:

Code:

# imports
import plotly.graph_objs as go
import pandas as pd
import numpy as np

# data
df1 = pd.DataFrame({'index': ['1','2','3'], 'A': [10,10,12], 'B': [11,11,11]})
df2 = pd.DataFrame({'index': ['1','2','3'], 'A': [10,10,10], 'B': [11,11,12]})

# plotly figure setup
fig=go.Figure()
fig.add_trace(go.Scatter(x=df1['index'], y=df1['A'], mode='lines'))
fig.add_trace(go.Scatter(x=df1['index'], y=df1['B'], mode='lines'))

f=fig.to_dict()
#fig.show()

buttons=list([dict(args=[{'y':[df1['A'],df1['B']]}],
                    
                   label="df1",
                   method="restyle"
                ),
                dict(args=[{'y':[df2['A'], df2['B']]}],
                    
                    label="df2",
                    method="restyle"
                )
            ])

fig.update_layout(
    updatemenus=[
        go.layout.Updatemenu(
            buttons=buttons,
            direction="down",
            pad={"r": 10, "t": 10},
            showactive=True,
            x=-0.25,
            xanchor="left",
            y=1,
            yanchor="top"
        ),
    ]
)

fig.show()

In the snippet above, I'm updating the 'y' values using buttons and dict(args=[{'y':[df2['A'], df2['B']]}]. This assigns new values to both traces specified within the figure like this fig-to_dict:

'data': [{'mode': 'lines',
   'x': array(['1', '2', '3'], dtype=object),
   'y': array([10, 10, 12], dtype=int64),
   'type': 'scatter'},
  {'mode': 'lines',
   'x': array(['1', '2', '3'], dtype=object),
   'y': array([11, 11, 11], dtype=int64),
   'type': 'scatter'}]

Since I've assigned the list [df2['A'], df2['B']] to 'y', plotly knows that I intend to update both instances of 'y' in the snippet above. But within the context of buttons and update menus, is there a way I can specify which 'y' to update (in other words: what specific trace or line). If I assign only one reference (array or pandas dataframe in this case), both traces will show the same values. So changing the following part:

 args=[{'y':[df2['A'], df2['B']]}]

...with this:

args=[{'y':[df2['A']]}]

... will produce the following plot upon clicking df2:

And I'd really like to keep all unspecified 'y' and traces unchanged.

Thank you for any suggestions!

解决方案

In the list you are passing to args for each button, you can add an integer after the dict to indicate which trace you want to update. For example the following will update the first trace only (i.e. the one at index=0)

buttons=list([dict(args=[{'y':[df1['A'],df1['B']]}, [0]], # note the `, [0]` here!

                   label="df1",
                   method="restyle"
                ),
                dict(args=[{'y':[df2['A'], df2['B']]}, [0], # note the `, [0]` here!

                    label="df2",
                    method="restyle"
                )
            ])

这篇关于Plotly:如何使用 updatemenus 更新一个特定的跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)