[英]Dynamically update the title in Dash Plotly
I have created this very simplified example in which I would like to dynamically update the title of a chart as a dropdown label changes.我创建了这个非常简化的示例,我想在下拉列表 label 更改时动态更新图表的标题。 Here's the code:
这是代码:
data = {'Stock': ['F', 'NFLX', 'AMZN'], 'Number': [10, 15, 7]}
df = pd.DataFrame(data, columns=['Stock', 'Number'])
stock_options = df['Stock']
app = dash.Dash(__name__)
app.layout = html.Div(children=[
html.H1(children='Example Bar Chart'),
html.Div([
dcc.Dropdown(
id='dropdown',
options=[{'label': i, 'value': i} for i in stock_options],
value='F',
),
html.Div(dcc.Graph(id='graph')),
]),
])
@app.callback(
Output(component_id='graph', component_property='figure'),
Input(component_id='dropdown', component_property='value')
)
def update_graph(stock):
msk = df.Stock.isin([stock])
figure = px.bar(df[msk], x='Stock', y='Number', title=f"{stock} open price")
return figure
if __name__ == '__main__':
app.run_server(debug=True)
So, while keeping the same label in dropdown instead of 'F open price' in the title I would like to get 'Facebook open price'... and so on.因此,虽然在下拉菜单中保持相同的 label 而不是标题中的“F 开盘价”,但我想获得“Facebook 开盘价”......等等。 I've tried to solve this with
map
but I couldn't get it working.我试图用
map
解决这个问题,但我无法让它工作。 Can someone point me in the direction on how to resolve this?有人可以指出如何解决这个问题的方向吗? Thanks in advance.
提前致谢。
As I wrote in my comment, not sure how you want to store the mapping between symbol name and the displayed title in the graph.正如我在评论中所写,不确定如何存储符号名称和图表中显示的标题之间的映射。 Here is one solution that works using a dictionary
stock_name_mapping
that contains the symbols als keys and the displayed names as values:这是一种使用字典
stock_name_mapping
工作的解决方案,其中包含符号 als 键和显示的名称作为值:
import pandas as pd
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc
import plotly.express as px
data = {'Stock': ['F', 'NFLX', 'AMZN'], 'Number': [10, 15, 7]}
df = pd.DataFrame(data, columns=['Stock', 'Number'])
stock_options = df['Stock']
stock_name_mapping = {'F': 'Facebook',
'NFLX': 'Netflix',
'AMZN': 'Amazon'}
app = dash.Dash(__name__)
app.layout = html.Div(children=[
html.H1(children='Example Bar Chart'),
html.Div([
dcc.Dropdown(
id='dropdown',
options=[{'label': i, 'value': i} for i in stock_options],
value='F',
),
html.Div(dcc.Graph(id='graph')),
]),
])
@app.callback(
Output(component_id='graph', component_property='figure'),
Input(component_id='dropdown', component_property='value')
)
def update_graph(stock):
msk = df.Stock.isin([stock])
stock_name = stock_name_mapping[stock]
figure = px.bar(df[msk], x='Stock', y='Number', title=f"{stock_name} open price")
return figure
if __name__ == '__main__':
app.run_server(debug=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.