plotly-dash快速⼊门
介绍
Dash is a productive Python framework for building web applications.
Written on top of Flask, Plotly.js, and React.js, Dash is ideal for building data visualization apps with highly custom user interfaces in pure Python. It's particuarly suited for anyone who works with data in Python.
Through a couple of simple patterns, Dash abstracts away all of the technologies and protocols that are required to build an interactive web-based application. Dash is simple enough that you can bind a user interface around your Python code Dash apps are rendered in the web browser. You can deploy your apps to servers and then share them through URLs. Since Dash apps are viewed in the web browser, Dash is inherently cross-platform and mobile ready.
There is a lot behind the framework. To learn more about how it is built and what motivated dash, watch our talk from Plotcon below or read our announcement letter.
Dash is an open source library, released under the permissive MIT license. Plotly develops Dash and o
ffers a platform for deploying, orchestrating, and permissioning dash apps in an enterprise environment
安装
In your terminal, install several dash libraries. These libraries are under active development, so install and upgrade frequently. Python 2 and 3 are supported.
pip install dash==0.17.7  # The core dash backend
pip install dash-renderer==0.7.4  # The dash front-end
pip install dash-html-components==0.7.0  # HTML components
pip install dash-core-components==0.7.1  # Supercharged components
pip install plotly==2.0.12  # Plotly graphing library used in
examples
Dash App Layout
Generating HTML with Dash
Dash apps are composed of two parts. The first part is the "layout" of the app and it describes what the application looks like. The second part describes the interactivity(内部联系) of the application.
Dash provides Python classes for all of the visual components of the application. We maintain a set of components in the dash_core_components and the dash_html_components library but you can also build your own with JavaScript
To get started, create a file named app.py with the following code:
main.py
# -*- coding: utf-8 -*-
'''
@Author: Elton
@File: app.py
千锋html5是什么意思
@Date: 2021-01-17
'''
import json
import numpy as np
import pandas as pd
import requests
from flask import Flask
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
aph_objs as go
press as px
server = Flask(__name__)
# dash路由:
app0 = dash.Dash(__name__, server=server, url_base_pathname='/demo/')
app1 = dash.Dash(__name__, server=server, url_base_pathname='/dash_bar/')
app2 = dash.Dash(__name__, server=server, url_base_pathname='/dash_plot/')grunt人设
app3 = dash.Dash(__name__, server=server, url_base_pathname='/dash_pie/')
# 模拟全部数据
l1 = ["2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-05", "2021-01-06", "2021-01-07"]
l2 = [1, 2, 3, 4, 5, 6, 7]
l3 = ["1.今天(1⽉16⽇)下午,河北省召开第六场疫情防控新闻发布会,对疫情防控相关情况进⾏通报。",
"2.河北新增32例本⼟确诊病例。",
"3.发布会上,相关负责⼈介绍,1⽉16⽇0—10时,河北省新增32例本⼟确诊病例。",
"""4.根据俄罗斯媒体RT的报道,红区及绿区包括⽩宫、林肯纪念堂、国家⼴场及国会附近的地区。绿区街道只准居民及商户通过,通过时必须出⽰个⼈⾝份证明,红区只准获授权车辆进⼊。约2.5万荷实弹的国民警卫队员被派驻到华盛顿,也就"5.声明:转载此⽂是出于传递更多信息之⽬的。若有来源标注错误或侵犯了您的合法权益。",
"6.宜昌市六届⼈⼤六次会议主席团举⾏第四次会议。",
"7.抗疫先锋⼁“疫情就是冲锋号要⽆所畏惧往前冲”。"]
# 模拟部分数据
alist1 = ["2021-01-01", "2021-01-04", "2021-01-05", "2021-01-06", "2021-01-07"]
alist2 = [1, 4, 5, 6, 7]
alist3 = ["1.今天(1⽉16⽇)下午,河北省召开第六场疫情防控新闻发布会,对疫情防控相关情况进⾏通报。",
"""4.根据俄罗斯媒体RT的报道,红区及绿区包括⽩宫、林肯纪念堂、国家⼴场及国会附近的地区。绿区街道只准居民及商户通过,通过时必须出⽰个⼈⾝份证明,红区只准获授权车辆进⼊。约2.5万荷实弹的国民警卫队员被派驻到华盛顿,"5.声明:转载此⽂是出于传递更多信息之⽬的。若有来源标注错误或侵犯了您的合法权益。",
"6.宜昌市六届⼈⼤六次会议主席团举⾏第四次会议。",
"7.抗疫先锋⼁“疫情就是冲锋号要⽆所畏惧往前冲”。"]
# 数据处理,可忽略
d = {"trade_dt": l1, "anal_yield": l2, "event_desc": l3}
df1 = pd.DataFrame(d)
d2 = {"trade_dt": alist1, "anal_yield": alist2, "event_desc": alist3}
df2 = pd.DataFrame(d2)
# 删除所有NaN的⾏
# df2 = pd.read_csv(r"/Users/wangcheng/Desktop/plotly_demo.csv", encoding="utf-8")
# print(f"df2:{df2}")
# df2 = df2.dropna(axis=0, how='any')
# print(f"df2:{df2}")
x = df1["trade_dt"]
y1 = df1["anal_yield"]
def foo(data, amount=50):
l = []
for d_i in list(data):
if d_i is not np.nan:
temp = ""
while True:
if not d_i:
break
temp += d_i[:amount]
d_i = d_i[amount:]
temp += "<br>"
l.append(temp)
return l
# default_fig = px.line(df1,
#                      x='trade_dt',
#                      y='anal_yield',
#                      # hover_data=["event_desc",],
#                      # hover_data=[foo(df["event_desc"]),],
#                      # render_mode="svg",
#                      template="plotly",  # 背景颜⾊
#                      text="event_desc",
#                      # text=foo(df["event_desc"]),
#                      labels={"trade_dt": "⽇期", "anal_yield": "收益率"},
#                      )
default_fig = px.line(
python入门教程appx=df1['trade_dt'],
y=df1['anal_yield'],
template="plotly",  # 背景颜⾊
# text="event_desc",
# labels={"trade_dt": "⽇期", "anal_yield": "收益率"},  # 第⼀个参数是df应该才是这种语法
labels=dict(x="⽇期", y="收益率", color="FigureOf"),
color=px.Constant("指标折线图"),
)
# ⾃定义 --> 控制悬浮⽂本宽度 Python Change size of hover text in Plotly
# 注:line和scatter都会影响到,⼀定要放在add_scatter之前
default_fig.update_traces(customdata=foo(df1["event_desc"]), textposition='top center')
default_fig.update_traces(hovertemplate='trade_dt: %{x} <br>anal_yield: %{y} <br>')  # ⽆需展⽰event_desc # 添加事件散点图
default_fig.add_scatter(
x=df2["trade_dt"],
y=df2["anal_yield"],
mode='markers',
# hovertext=df2["event_desc"],
# hovertext=foo(df1["event_desc"]),
line={"color": "orange", "width": 40},
name="事件散点图",
customdata=foo(df2["event_desc"]),
hovertemplate='trade_dt: %{x} <br>anal_yield: %{y} <br>event_desc: %{customdata}<br>',
)
default_fig.update_layout(
margin=dict(l=10, r=10, t=10, b=10),
hoverlabel=dict(font=dict(family='sans-serif', size=15)),
# uniformtext={"minsize": 10, "mode": "show"},
# autosize=True,
)
# 路由dash_bar的布局
app0.layout = html.Div([
html.Div(
children=[html.H1(children='收益率对⽐事件'), ]
),
linux系统安装mongodb
html.Label('Tag:'),
kali# 输⼊框
dcc.Input(
id="input-target-id",
placeholder='Enter ',  # 隐式默认值,但是回调值是None
type='text',
value=''# 显式默认值,回调值就是这个值
),
# 单选框
# dcc.RadioItems(
#    id='hovermode',
#    labelStyle={'display': 'inline-block'},
#    options=[{'label': x, 'value': x}
#              for x in ['x', 'x unified', 'closest']],
#    value='closest'
# ),
dcc.Graph(id="graph-demo", figure=default_fig),  # 回调函数⾥改figure属性值
])
# 路由dash_bar的布局
app1.layout = html.Div([
html.Div(
children=[html.H1(children='趋势 1'), ]
)
,
dcc.Graph(
id='example-graph',
figure={
'data': [
{'x': x, 'y': y1, 'type': 'bar', 'name': '取消或推迟发⾏规模(亿元)'},
],
'layout': {
'title': 'Dash Data Visualization柱状可视化'
}
}
)
,
])
# 路由dash_plot的布局
app2.layout = html.Div([
html.Div(
children=[html.H1(children='趋势 2'), ]
),
dcc.Graph(
id='example-graph',
figure={
'data': [
{'x': x, 'y': y1, 'type': 'plot', 'name': u'取消或推迟发⾏规模只数(个)', "text": foo(df1["event_desc"]),                },
],
'layout': {
'title': 'Dash Data Visualization柱状可视化',
"hovermode": "closest",
}
}
),
])
# 路由dash_pie的布局
app3.layout = html.Div([
html.Div(
children=[html.H1(children='趋势 3'), ]
),
grubdcc.Graph(
id='pie',
figure={
'data': [
dict(
type='pie', name='Pie',
# labels=tmp['group1'].tolist(),
# values=tmp['num'].tolist(),
labels=["张三", "李四", "王五", "⽼六"],
values=[18, 24, 36, 99],
)
],
'layout': {
'title': 'Dash Data Visualization饼图可视化'
}
}
),
])
# 回调函数
@app1.callback(
Output("graph", "figure"),
[Input("input-target-id", "value")],
)
def update_data_by_tag(*args, **kwargs):
print("暂不⽣效,不⾛回调也不打印,你被骗了~~")
print(f"args: {args}")
print(f"kwargs: {kwargs}")
return
# flask路由
@ute('/test')
def do_test():
return"this is test route"
@ute('/')
def do_main():
return"main"
if__name__ == '__main__':
server.run(debug=True, port=8051, host="0.0.0.0")
如图:
解决Python Change size of hover text in Plotly问题
解决 jupyter notebook画图画不出,添加该⾏代码:
import plotly  as py
py.offline.init_notebook_mode()  # 允许在jupyter notebook⾥边绘plotly的图
# py.offline.iplot(mydataframe, filename='电脑的⽂件存放路径.html') # 改⾏是执⾏正在更新中……

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。