文章目录
视频讲解:
<iframe allowfullscreen="true" data-mediaembed="csdn" id="n2DLi9UU-1635052017115" src="https://live.csdn.net/v/embed/179123"></iframe>【Python百日基础系列】22 - Dash布局实例(二)
三、Dash布局实例(续)
Dash 包括“热重载”,当您使用app.run_server(debug=True). 这意味着当您更改代码时,Dash 会自动刷新您的浏览器。
可以使用app.run_server(dev_tools_hot_reload=False)。关闭“热重载”功能。
3.2 实例2:自定义HTML文本样式
# _*_ coding: UTF-8 _*_
# @Time:2021/10/20 21:12
# @Author:岳涛@心馨电脑
# @File:Day21 - Dash基础.py
# @Software:PyCharm
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.
import dash
from dash import dcc
from dash import html
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Amount": [4, 1, 2, 2, 4, 5],
"City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})
fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")
fig.update_layout(
plot_bgcolor=colors['background'],
paper_bgcolor=colors['background'],
font_color=colors['text']
)
app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
html.H1(
children='Hello Dash',
style={
'textAlign': 'center',
'color': colors['text']
}
),
html.Div(children='Dash: A web application framework for your data.', style={
'textAlign': 'center',
'color': colors['text']
}),
dcc.Graph(
id='example-graph-2',
figure=fig
)
])
if __name__ == '__main__':
app.run_server(debug=True)
浏览器效果:
说明:
dash_html_components(dash.html从 Dash v2.0 开始)包含每个 HTML 标签的组件类以及所有 HTML 参数的关键字参数。
在这个例子中,我们使用属性修改了html.Div 和html.H1组件的内联样式 style。
html.H1('Hello Dash', style={'textAlign': 'center', 'color': '#7FDBFF'})
dash_html_components(dash.html从 Dash v2.0 开始) 和 HTML 属性之间有一些重要的区别:
styleHTML 中的属性是一个以分号分隔的字符串。在 Dash 中,你可以只提供一个字典。
style字典中的键是驼峰式的。所以,而不是text-align,它是textAlign。
HTMLclass属性className在 Dash 中。
HTML 标签的子标签是通过children关键字参数指定的。按照惯例,这始终是第一个参数,因此经常被省略。
除此之外,您可以在 Python 上下文中使用所有可用的 HTML 属性和标签。
3.3 实例3:表格
# _*_ coding: UTF-8 _*_
# @Time:2021/10/20 21:12
# @Author:岳涛@心馨电脑
# @File:Day21 - Dash基础.py
# @Software:PyCharm
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.
import dash
from dash import html
import plotly.express as px
import pandas as pd
# csv_url = 'https://gist.githubusercontent.com/chriddyp/c78bf172206ce24f77d6363a2d754b59/raw/c353e8ef842413cae56ae3920b8fd78468aa4cb2/usa-agricultural-exports-2011.csv'
df = pd.read_csv('data/usa-agricultural-exports-2011.csv')
def generate_table(dataframe, max_rows=10):
return html.Table([
html.Thead(
html.Tr([html.Th(col) for col in dataframe.columns])
),
html.Tbody([
html.Tr([
html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
]) for i in range(min(len(dataframe), max_rows))
])
])
app = dash.Dash(__name__)
app.layout = html.Div([
html.H4(children='US Agriculture Exports (2011)'),
generate_table(df)
])
if __name__ == '__main__':
app.run_server(debug=True)
浏览器效果:
说明
在Python中定义方法,Dash通过调用,可以创建复杂的可重用组件,如表格等,无需切换上下文或语言;
本示例实现的功能,是从Pandas的数据帧生成“表格”。
3.4 实例4:散点图
# _*_ coding: UTF-8 _*_
# @Time:2021/10/20 21:12
# @Author:岳涛@心馨电脑
# @File:Day21 - Dash基础.py
# @Software:PyCharm
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.
import dash
from dash import dcc
from dash import html
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
# csv_url = 'https://gist.githubusercontent.com/chriddyp/5d1ea79569ed194d432e56108a04d188/raw/a9f9e8076b837d541398e999dcbac2b2826a81f8/gdp-life-exp-2007.csv'
df = pd.read_csv('data/gdp-life-exp-2007.csv')
fig = px.scatter(df, x="gdp per capita", y="life expectancy",
size="population", color="continent", hover_name="country",
log_x=True, size_max=60)
app.layout = html.Div([
dcc.Graph(
id='life-exp-vs-gdp',
figure=fig
)
])
if __name__ == '__main__':
app.run_server(debug=True)
浏览器效果:
说明
dash_core_components 库包含一个名为的组件Graph,其使用开源JavaScript图形库plotly.js ,呈现交互式数据可视化;
Plotly.js 支持超过35种图表类型,并以矢量质量SVG和高性能WebGL的方式呈现图表;
dash_core_components.Graph 组件的参数 figure ,与开放源码的 Python 图形库 Plotly 中的参数 figure使用方法,都是一样的;
这些图表具有互动性和响应性:
将鼠标悬停在点上以查看其值;
单击图例项以切换轨迹;
单击并拖动以缩放;
按住shift后单击并拖动,可以平移图表;
3.5 实例5:Markdown
# _*_ coding: UTF-8 _*_
# @Time:2021/10/20 21:12
# @Author:岳涛@心馨电脑
# @File:Day21 - Dash基础.py
# @Software:PyCharm
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.
import dash
from dash import dcc
from dash import html
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
markdown_text = '''
### Dash and Markdown
Dash apps can be written in Markdown.
Dash uses the [CommonMark](http://commonmark.org/)
specification of Markdown.
Check out their [60 Second Markdown Tutorial](http://commonmark.org/help/)
if this is your first introduction to Markdown!
'''
app.layout = html.Div([
dcc.Markdown(children=markdown_text)
])
if __name__ == '__main__':
app.run_server(debug=True)
浏览器效果
说明
虽然Dash通过 dash_html_components 库可以实现文本编写,但在HTML中编写文本,比较繁琐,需要写入大量的格式化文本,推荐使用库中的Markdown组件;
Dash使用 Markdown 的CommonMark规范;
补充视频代码:
import plotly.express as px
import pandas as pd
import dash
from dash import dcc
from dash import html
class MyDash:
def __init__(self):
self.fig = ''
self.df1 = ''
self.colors = {
'background': '#111111',
'text': '#7FDBFF'
}
self.dash_data()
self.dash_layout()
def dash_data(self):
""" 数据与业务逻辑处理 """
df = pd.read_excel('fruit.xlsx', sheet_name='Sheet2')
df.columns = ['fruit', 'year', 'amount']
self.fig = px.bar(df, x='fruit', y='amount', color='year', barmode='group')
self.fig.update_layout(
plot_bgcolor=self.colors['background'],
paper_bgcolor=self.colors['background'],
font_color=self.colors['text']
)
# csv_url = 'https://gist.githubusercontent.com/chriddyp/c78bf172206ce24f77d6363a2d754b59/raw/c353e8ef842413cae56ae3920b8fd78468aa4cb2/usa-agricultural-exports-2011.csv'
self.df1 = pd.read_csv('usa-agricultural-exports-2011.csv')
# csv_rul = 'https://gist.githubusercontent.com/chriddyp/5d1ea79569ed194d432e56108a04d188/raw/a9f9e8076b837d541398e999dcbac2b2826a81f8/gdp-life-exp-2007.csv'
self.df2 = pd.read_csv('gdp-life-exp-2007.csv')
self.fig2 = px.scatter(self.df2, x="gdp per capita", y="life expectancy",
size="population", color="continent", hover_name="country",
log_x=True, size_max=60)
a = 200
self.markdown_text = f'''视频讲解:{a}
# 一、Dash简介
Dash是一个用于构建Web应用程序的高效Python框架。
Dash写在Flask,Plotly.js和React.js之上,在纯Python中,使用高度自定义的用户界面,构建数据可视化应用程序。
它特别适合使用Python进行数据分析的人。
Dash官网:[https://dash.plotly.com](https://dash.plotly.com)
'''
def generate_table(self, df, max_rows=10):
return html.Table([
html.Thead(html.Tr([html.Th(col) for col in df.columns])),
html.Tbody([html.Tr([html.Td(df.iloc[i][col]) for col in df])
for i in range(min(len(df), max_rows))])
])
def dash_layout(self):
""" Dash页面布局 """
app.layout = html.Div(
id='example-div',
style={'backgroundcolor': self.colors['background']},
children=[
html.H1(
id='example-h1',
style={'textAlign': 'center', 'color': self.colors['text']},
children='2017-2019年水果销量图'),
html.Div(
id='example-sub-title',
style={'textAlign': 'center', 'color': self.colors['text']},
children='常用水果'),
dcc.Graph(
id='example-fruit',
figure=self.fig),
html.Hr(),
html.H4('美国农业常量(2011)'),
self.generate_table(self.df1),
html.Hr(),
dcc.Graph(id='life-exp-vs-gdp',
figure=self.fig2),
html.Hr(),
dcc.Markdown(self.markdown_text),
])
if __name__ == '__main__':
app = dash.Dash(__name__)
MyDash()
app.run_server(debug=True)