章關鍵字:Python做Web網頁開發、Dash開源庫Bootstrap用法、折疊面板插件Collapse用法
本章節我們介紹下Python數據可視化Dash框架中Dash Bootstrap Components開源庫中Bootstrap折疊面板插件Collapse的基本用法。
在此之前,我們先來了解下“Collapse”插件基本內容。
使用Collapse組件切換應用程序中內容的可見性,通過純Python編寫的Demo效果:
接下來,介紹下該控件主要函數的用法,主要用到Dash Bootstrap控件庫中的Collapse()函數,具體參數如下。
以下是該函數的主要參數:
import dash_bootstrap_components as dbc
from dash import html, Input, Output, State
from server import app
collapse_html=html.Div(
[
html.Br(),
html.P(html.Strong('使用Collapse組件切換應用程序中內容的可見性', style={'color': 'rgb(255, 153, 51)'})),
html.Br(),
dbc.Button('展示/隱藏', color='primary', id='collapse_btn', className="me-1", n_clicks=0),
html.Hr(),
dbc.Collapse(
dbc.Card('這個是Collapse內容的展示', body=True),
id='collapse',
is_open=True,
)
]
)
@app.callback(
Output('collapse', 'is_open'),
[Input('collapse_btn', 'n_clicks')],
[State('collapse', 'is_open')]
)
def toggle(n, is_open):
return not is_open
結合代碼示例,可以調試體驗下該插件的用法,如果想了解更多內容,可關注我,對于整個示例的Demo可私信我獲取。
說明:
======
1.1 今天白天發過有關Dash的文章,發現有問題,先撤回,再刪除。雖然會嚴重影響推薦,但是為了讀者負責任,我愿意承擔這樣,不在乎推薦。所以喜歡的,請點贊、關注、轉發、評論和收藏。
1.2 Dash是一個純Python寫成的框架,無需JavaScript即可構建交互式的分析類web應用程序。
1.3 Dash是一個優秀的交互式可視化工具,基于plotly。
1.4 python可視化庫plotly生態簡介(plotly, plotly_express, dash)。
2 安裝:
=====
pip install dash==1.12.0
#本機安裝
pip3.8 install dash #我任性一點,不指定版本安裝
3 官網:
=====
https://github.com/plotly/dash
https://plotly.com/dash #本機太卡,基本沒進去過
https://dash-gallery.plotly.host/Portal/
4 基本作圖:
=========
4.1 柱狀圖bar:
===========
4.1.1 代碼:
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
#external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css'] #方法三
#app=dash.Dash(__name__, external_stylesheets=external_stylesheets) #方法三
#app=dash.Dash(__name__) #方法二
app=dash.Dash() #注意等同于上面,方法一
#html的div容器布局
app.layout=html.Div(
children=[
#h1文字,這個與Html的h1~4的字體一樣
#html.H1(children='Hello Dash'),
html.H1('Hello Dash'), #同上面
#html.Label('Hello Dash'), #注意label與div的文本一樣,字體大小等
#文字
html.Div(children='''Dash: A web application framework for Python.'''),
#可視化作圖
dcc.Graph(
#id='example-graph', #如果布局較多的內容,id就很重要
figure={
'data': [
#type為bar---柱狀圖
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': '汽車'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': '火車'},
],
#title就是圖表的標題
'layout': {'title': 'Dash Data Visualization'}
}
)
])
if __name__=='__main__':
app.run_server(debug=True)
#其實是結合flask的在線可視化作圖
4.1.2 操作和效果圖:
4.2 折線圖line:
===========
4.2.1 代碼:
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
app=dash.Dash()
app.layout=html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
dcc.Graph(
id='example-graph',
figure={
'data': [
#由bar柱狀圖改為line折線圖,僅僅改type為line---折線圖
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'line', 'name': '汽車'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'line', 'name': '火車'},
],
'layout': {
'title': 'Dash Data Visualization'
}
}
)
])
if __name__=='__main__':
app.run_server(debug=True)
4.2.2 操作和效果圖:
4.3 散點圖Scatter:
==============
4.3.1 代碼:
import dash
import dash_core_components as dcc
import dash_html_components as html
app=dash.Dash()
app.layout=html.Div([
dcc.Graph(
figure={
'data': [
#A組數據
{
'x': [1, 2, 3, 4],
'y': [4, 1, 3, 5],
'text': ['雞', '鴨', '鵝', '鳥'],
'name': 'A組',
'mode': 'markers',
#散點圖大小設置
'marker': {'size': 20}
},
#B組數據
{
'x': [1, 2, 3, 4],
'y': [9, 4, 1, 4],
'text': ['豬', '狗', '牛', '羊'],
'name': 'B組',
'mode': 'markers',
#散點圖大小設置
'marker': {'size': 20}
}
],
'layout':
#圖表標題
{'title': 'Dash Data Visualization'}
}
),
])
if __name__=='__main__':
app.run_server(debug=True)
4.3.2 操作和效果圖:注意因為我的谷歌瀏覽器并沒有關閉,所以啟動后自動刷新。
4.4 高級散點圖Scatter:
==================
4.4.1 代碼:
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
app=dash.Dash()
#在線csv地址和引用
'''
df=pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/' +
'5d1ea79569ed194d432e56108a04d188/raw/' +
'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+
'gdp-life-exp-2007.csv')
'''
#將數據csv下載到本地的引用
df=pd.read_csv('/home/xgj/Desktop/dash/gdp-life-exp-2007.csv')
app.layout=html.Div([
dcc.Graph(
id='life-exp-vs-gdp',
figure={
'data': [
go.Scatter(
x=df[df['continent']==i]['gdp per capita'],
y=df[df['continent']==i]['life expectancy'],
text=df[df['continent']==i]['country'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
name=i)for i in df.continent.unique()
],
'layout': go.Layout(
xaxis={'type': 'log', 'title': 'GDP Per Capita'},
yaxis={'title': 'Life Expectancy'},
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
legend={'x': 0, 'y': 1},
hovermode='closest')
}
)
])
if __name__=='__main__':
app.run_server(debug=True)
4.4.2 操作和效果圖:
5 控件:
=====
5.1 代碼:
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
app=dash.Dash()
app.layout=html.Div([
#展示1:
html.Label('Dropdown=下拉菜單'),
dcc.Dropdown(
options=[
{'label': '太陽', 'value': 'SUN'},
{'label': '地球', 'value': 'EARTH'},
{'label': '月亮', 'value': 'MOON'}
],
value='SUN' #初始值
),
#展示2:
html.Label('Multi-Select Dropdown=多選菜單'),
dcc.Dropdown(
options=[
{'label': '太陽', 'value': 'SUN'},
{'label': '地球', 'value': 'EARTH'},
{'label': '月亮', 'value': 'MOON'}
],
#初始值顯示對應的label
value=['SUN', 'MOON'],
multi=True
),
#展示3:
html.Label('Radio Items=單選菜單'),
dcc.RadioItems(
options=[
{'label': '太陽', 'value': 'SUN'},
{'label': '地球', 'value': 'EARTH'},
{'label': '月亮', 'value': 'MOON'}
],
value='MTL'
),
#展示4:
html.Label('Checkboxes=復選菜單'),
dcc.Checklist(
options=[
{'label': '太陽', 'value': 'SUN'},
{'label': '地球', 'value': 'EARTH'},
{'label': '月亮', 'value': 'MOON'}
],
value=['MTL', 'SF']
),
#展示5:
html.Label('Slider=滑動條'),
dcc.Slider(
min=0,
max=9,
marks={i: 'Label {}'.format(i) if i==0 else str(i) for i in range(0, 10)},
#初始值
value=5,
),
],
#代表1列;2代表2列;3代表3列=column
style={'columnCount': 1})
if __name__=='__main__':
app.run_server(debug=True)
5.2 操作和效果圖:
6 表格table:
=========
6.1 代碼:
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
'''
#在線引用
df=pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/'
'c78bf172206ce24f77d6363a2d754b59/raw/'
'c353e8ef842413cae56ae3920b8fd78468aa4cb2/'
'usa-agricultural-exports-2011.csv')
'''
#下載到本地,引用
df=pd.read_csv('/home/xgj/Desktop/dash/usa-agricultural-exports-2011.csv')
#定義產生表格函數
def generate_table(dataframe, max_rows=10):
#返回值是一個表格
return html.Table(
# Header=表頭
[html.Tr([html.Th(col) for col in dataframe.columns])] +
# Body=表體
[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()
app.layout=html.Div(children=[
html.H4(children='US Agriculture Exports (2011年)'), #故意中英文混合,提示支持中文
generate_table(df) #引用自定義函數
])
if __name__=='__main__':
app.run_server(debug=True)
6.2 操作和效果圖:
7 回調callback:
============
7.1 代碼:
import dash
import dash_core_components as dcc
import dash_html_components as html
app=dash.Dash()
app.layout=html.Div([
dcc.RadioItems(
id='dropdown-a',
options=[{'label': i, 'value': i} for i in ['馬', '牛', '羊']],
value='馬'
),
html.Div(id='output-a'),
dcc.RadioItems(
id='dropdown-b',
options=[{'label': i, 'value': i} for i in ['雞', '鴨', '鵝']],
value='鴨'
),
html.Div(id='output-b')
])
@app.callback(
dash.dependencies.Output('output-a', 'children'),
[dash.dependencies.Input('dropdown-a', 'value')])
#定義函數回調a
def callback_a(dropdown_value):
#注意python的轉義字符\',就是顯示'
return 'You\'ve selected "{}"'.format(dropdown_value)
@app.callback(
dash.dependencies.Output('output-b', 'children'),
[dash.dependencies.Input('dropdown-b', 'value')])
def callback_b(dropdown_value):
return 'You\'ve selected "{}"'.format(dropdown_value)
if __name__=='__main__':
app.run_server()
7.2 操作和效果圖:
===自己整理并分享出來===
喜歡的就點贊、關注、轉發、評論和收藏。
估計推薦量不高,沒關系,我自己覺得修改后的更好。
章關鍵字:Python做Web網頁開發、Dash開源庫Bootstrap、信息提示框用法、Bootstrap庫Alert函數用法
本章節我們來了解了Python數據可視化Dash框架中的開源庫Dash Bootstrap Components組件中信息提示框Alert的基本用法,使用Alert組件為用戶操作提供上下文反饋消息。
信息提示框也可以叫做警告框,警告框通常用于輸出一些對用戶的提示信息,比如在用戶輸入了錯誤格式數據時,警告提醒一下用戶原因。
接下來,我們來介紹一下Alert這個控件,以及在Python中如何使用Alert,我簡單寫了一個Demo,效果如下圖展示(如果想了解更多內容,可以關注我,對于整個示例的Demo可私信我獲取),
此控件的Demo代碼如下所示,更多內容可私信我:
import dash_bootstrap_components as dbc
from dash import html, Input, Output, State
from server import app
alert_html=html.Div([
html.Br(),
html.P(html.Strong('使用Alert組件為用戶操作提供上下文反饋消息, 提醒控件', style={'color': 'rgb(255, 153, 51)'})),
dbc.Button('關閉或顯示一條警報', id='alert-toggle', className='me-1', n_clicks=0),
html.Hr(),
dbc.Alert('我是一條警報',
id='alert-fade',
dismissable=True, # 為警報添加一個解除按鈕,單擊后關閉警報
is_open=True,
fade=True,
duration=2000, # 警報自動解除的時間,配合fade=True時使用
color='warning'),
])
@app.callback(
Output('alert-fade', 'is_open'),
[Input('alert-toggle', 'n_clicks')],
[State('alert-fade', 'is_open')]
)
def toggle_alert(n, is_open):
if n:
return not is_open
return is_open
接下來,我們來詳細介紹下這alert組件的一些參數
我們可以對應Demo代碼,理解各個參數的含義,如果想了解更多內容,可關注我,對于整個示例的Demo可私信我獲取。
*請認真填寫需求信息,我們會在24小時內與您取得聯系。