如何使用下拉菜单更新绘图标题? 完整代码:

问题描述

我希望绘图标题根据下拉列表中的选定值动态更改。 下面的代码可以很好地更新图表本身,但不会更改标题

我也试过用 {'layout_title_text': 'Title 1'} 代替 {'layout':{'title': {'text': 'Title 1'}}} 但也没有用。

pio.renderers.default = 'notebook'
    
import plotly.graph_objects as go
from plotly.subplots import make_subplots

p = go.figure()

y_values = ['label1','label2','label3']

x_values1 = [1,5,3]
x_values2 = [4,3,5]

p = p.add_trace(go.Bar(x = x_values1,y = y_values,orientation='h' 
               ))

updatemenus = [{'buttons': [{'method': 'update','label': 'Values 1','args': [{'x': [x_values1]},{'layout':{'title': {'text': 'Title 1'}}}
                                       ]
                                      },{'method': 'update','label': 'Values 2','args': [{'x': [x_values2]},{'layout':{'title': {'text': 'Title 2'}}}
                                     ]
                            }                         
                           ],'direction': 'down','showactive': True}]

p = p.update_layout(template = 'plotly_white',updatemenus=updatemenus
                   )

p.show()

解决方法

只需将 'layout'={} 放入您的设置中:

'args': [{'x': [x_values1]},{'title': {'text': 'Title 1'}}
       ]
      },

结果:

enter image description here

对于第二个选项:

enter image description here

完整代码:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

p = go.Figure()

y_values = ['label1','label2','label3']

x_values1 = [1,5,3]
x_values2 = [4,3,5]

p = p.add_trace(go.Bar(x = x_values1,y = y_values,orientation='h' 
               ))

updatemenus = [{'buttons': [{'method': 'update','label': 'Values 1','args': [{'x': [x_values1]},{'title': {'text': 'Title 1'}}
                                       ]
                                      },{'method': 'update','label': 'Values 2','args': [{'x': [x_values2]},{'title': {'text': 'Title 2'}}
                                     ]
                            }                         
                           ],'direction': 'down','showactive': True}]

p = p.update_layout(template = 'plotly_white',updatemenus=updatemenus
                   )

p.update_layout(title_text = 'Title 1')
p.show()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...