今天小编来为大家安利另外一个用于绘制可视化图表的 Dash框架中的两个基本概念我们先来了解一下
<h1>Hello World!!</h1> <div> <p>Dash converts Python classes into HTML</p> </div> </div> 我们转化成
安装和导入模块! pip install dash-html-components ! pip install dash-core-components ! pip install plotly dash-html-components 用来生成HTML 标签,dash-core-components 模块用来生成例如下拉框、输入框等组件,这里我们还需要用到plotly 模块,因为我们需要用到的数据来自该模块,里面是一众互联网公司过去一段时间中股价的走势
读取数据并且绘制折线图plotly 来绘制折线图,代码如下:df = px.data.stocks() #读取股票数据 def stock_prices(): # 绘制折线图 fig = go.Figure([go.Scatter(x=df['date'], y=df['AAPL'], line=dict(color='firebrick', width=4), name='Apple') ]) fig.update_layout(title='股价随着时间的变幻', xaxis_title='日期', yaxis_title='价格' ) return fig app.layout = html.Div(id='parent', children=[ html.H1(id='H1', children='Dash 案例一', style={'textAlign': 'center', 'marginTop': 40, 'marginBottom': 40}), dcc.Graph(id='line_plot', figure=stock_prices()) ]) if __name__ == '__main__': app.run_server() Dash 框架中的Div 方法来进行页面的布局,其中有参数id 来指定网页中的元素,以及style 参数来进行样式的设计,最后我们将会指出来的图表放在dcc.Graph() 函数当中。添置一个下拉框
options 参数中的label 对应的是下拉框中的各个标签,而value 对应的是DataFrame 当中的列名添加回调函数
我们看到 最后,全部的代码如下所示 import dash_html_components as html import dash_core_components as dcc import plotly.graph_objects as go import plotly.express as px from dash.dependencies import Input, Output app = dash.Dash() df = px.data.stocks() app.layout = html.Div(id='parent', children=[ html.H1(id='H1', children='Dash 案例一', style={'textAlign': 'center', 'marginTop': 40, 'marginBottom': 40}), dcc.Dropdown(id='dropdown', options=[ {'label': '谷歌', 'value': 'GOOG'}, {'label': '苹果', 'value': 'AAPL'}, {'label': '亚马逊', 'value': 'AMZN'}, ], value='GOOG'), dcc.Graph(id='bar_plot'), ]) @app.callback(Output(component_id='bar_plot', component_property='figure'), [Input(component_id='dropdown', component_property='value')]) def graph_update(dropdown_value): print(dropdown_value) fig = go.Figure([go.Scatter(x=df['date'], y=df['{}'.format(dropdown_value)], line=dict(color='firebrick', width=4)) ]) fig.update_layout(title='股价随着时间的变幻', xaxis_title='日期', yaxis_title='价格' ) return fig if __name__ == '__main__': app.run_server() |
|