by Anuj Pahade
由Anuj Pahade
Dash的快速入门将使您在5分钟内进入“ Hello World” (This quick intro to Dash will get you to “Hello World” in under 5 minutes)
Dash is an open source library for creating reactive apps in Python. You can create amazing dashboards in your browser using Dash.
Dash是一个开源库,用于在Python中创建React式应用程序。 您可以使用Dash在浏览器中创建惊人的仪表板。
The Iris data set can be called the ‘hello world’ of data sets. In this article, we’ll learn how to build a simple Dash app in which we’ll use the Iris data set. This data set is clean, which is good for us so that we can focus on dashing instead of cleaning the data.
Iris数据集可以称为数据集的“ hello world”。 在本文中,我们将学习如何构建一个简单的Dash应用程序,并在其中使用Iris数据集。 该数据集很干净,这对我们有好处,因此我们可以专注于破折号而不是清理数据。
破折号设定 (Dash setup)
To build cool apps, you need hot libraries.
要构建出色的应用程序,您需要热库。
If you have not already installed Dash, then run these commands in your terminal :
如果尚未安装Dash,请在终端中运行以下命令 :
pip install dash==0.21.1 # The core dash backend
pip install dash-renderer==0.12.1 # The dash front-end
pip install dash-html-components==0.10.1 # HTML components
pip install dash-core-components==0.22.1 # Supercharged components
pip install plotly --upgrade
pip install dash==0.21.1 # The core dash backend
pip install dash-renderer==0.12.1 # The dash front-end
pip install dash-html-components==0.10.1 # HTML components
pip install dash-core-components==0.22.1 # Supercharged components
pip install plotly --upgrade
Run your app as :
以以下方式运行您的应用程序:
python helloiris.py
Be clear with your Python versions.
明确说明您的Python版本。
应用布局 (App layout)
We can build the layout with the dash_html_components
library and the dash_core_components
library. I have imported them as shown above. The dash_html_components
is for all HTML tags, whereas the latter one is for interactive components built with React.js. Having said that, let’s write something in our browser using Dash:
我们可以使用dash_html_components
库和dash_core_components
库来构建布局。 我已经如上所示导入了它们。 dash_html_components
适用于所有HTML标签,而后者适用于使用React.js构建的交互式组件。 话虽如此,让我们使用Dash在浏览器中编写一些内容:
app.layout = html.Div(children=[ html.H1(children='Iris visualization'), html.Div( ''' Built with Dash: A web application framework for Python. ''')])
Yes! That’s how easy it is. The equivalent HTML code would look like this:
是! 就是这么简单。 等效HTML代码如下所示:
<div> <h1> Iris visualization </h1> <div> Built with Dash: A web application framework for Python. </div></div>
Notice the children
attribute in the first Div
. It is used to define the list
of elements enclosed in that tag. This is a positional argument (always comes first) and can be skipped as you can see in the next H1
and Div
shown above.
注意第一个Div
的children
属性。 它用于定义该标签中包含的元素list
。 这是一个位置自变量(始终是第一个),可以跳过,如您在上面显示的下一个H1
和Div
看到的。
Can we style it? I hear you ask. Well, of course! Dash allows you to write style dictionaries as you would write in a <sty
le> tag in HTML. It also lets you write inline CSS and link external CSS files. Here is how we can do it.
我们可以样式吗? 我听到你问。 嗯,当然! Dash允许您编写样式字典,就像在HTML中的<sty
le>标记中编写一样。 它还允许您编写内联CSS并链接外部CSS文件。 这是我们可以做到的。
风格字典 (Style dictionaries)
Let’s create a dictionary called colors.
让我们创建一个称为颜色的字典。
colors = { 'background': '#0000FF', 'color': '#FFA500'}
It can be attached with an element using the style
attribute as shown.
如图所示,可以使用style
属性将其附加到元素上。
app.layout = html.Div(style=colors,children=[ html.H1(children='Iris visualization'), html.Div( ''' Built with Dash: A web application framework for Python. ''')])
内联CSS (Inline CSS)
In Dash, the keys of dictionaries are camelCased
. So instead of text-align
we use textAlign
. Also the class
attribute of HTML tags is className
as you might know if you use React.
在Dash中,字典的键是camelCased
。 因此,我们使用textAlign
代替text-align
。 如果使用React,HTML标记的class
属性也是className
。
app.layout = html.Div(style=colors,children=[ html.H1(children='Iris visualization',style = {'textAlign':'center'}),
html.Div(style={'textAlign':'center'},children=''' Built with Dash: A web application framework for Python. ''')])
外部CSS (External CSS)
We can create a list of URLs or paths to CSS files we want to include in our Dash app, and then use app.css.append_css
to include them.
我们可以创建URL列表或指向要包含在Dash应用程序中CSS文件的路径,然后使用app.css.append_css
包含它们。
external_css = ["https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" ]
for css in external_css: app.css.append_css({"external_url": css})
We can include JavaScript in the exact same way by using app.scripts.append_script
我们可以使用app.scripts.append_script
以完全相同的方式包含JavaScript
I hope you’re with me till now! This is how our helloiris.py file looks:
希望您一直与我在一起! 这是我们的helloiris.py文件的外观:
import dashimport dash_core_components as dccimport dash_html_components as html
app = dash.Dash()
#External CSSexternal_css = ["https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css", ]
for css in external_css: app.css.append_css({"external_url": css})
#External JavaScriptexternal_js = ["http://code.jquery.com/jquery-3.3.1.min.js", "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"]
for js in external_js: app.scripts.append_script({"external_url": js})
#Internal CSScolors = { 'background': '#0000FF', 'color': '#FFA500'}
#Our app's Layoutapp.layout = html.Div(style=colors,children=[ html.H1(children='Iris visualization',style={'textAlign':'center'}),
html.Div(style={'textAlign':'center'},children=''' Built with Dash: A web application framework for Python. ''')])
if __name__ == '__main__': app.run_server(debug=True)
让我们获取一些数据 (Let’s get some data)
Assuming you’re familiar with pandas, we’ll use this Python library to import the iris.csv file in our app. If you don’t know what this dataset is about, then I recommend that you read and download it from here.
假设您熟悉熊猫,我们将使用此Python库在我们的应用程序中导入iris.csv文件。 如果您不知道此数据集的含义,那么建议您从此处阅读并下载。
import pandas as pd
header_names =[ 'sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']
df = pd.read_csv('path/to/Iris.csv',names=header_names)
Now that our data is loaded into the df
dataframe, it’s time for visualisation.
现在,我们的数据已加载到df
数据帧中,是时候进行可视化了。
数据可视化 (Data visualization)
Remember the interactive components I told you about? The dash_core_components
library? Well that’s what we are going to use here.
还记得我告诉过你的互动组件吗? dash_core_components
库? 嗯,这就是我们在这里要使用的。
import plotly.graph_objs as go
Let’s add a new component to our app.layout
. This time it’s not an HTML tag but an interactive graph. Dash uses Plotly to plot graphs.
让我们向app.layout
添加一个新组件。 这次,它不是HTML标记,而是交互式图形。 Dash使用Plotly绘制图形。
dcc.Graph( id='Iris Viz', figure={ 'data': [ go.Scatter( x=df[df['class'] == i]['petal_length'], y=df[df['class'] == i]['sepal_length'], mode='markers', opacity=0.7, marker={ 'size': 15, 'line': {'width': 0.5, 'color': 'white'} }, name=i ) for i in df['class'].unique() ], 'layout': go.Layout( xaxis={'title': 'Petal Length'}, yaxis={'title': 'Sepal Length'}, margin={'l': 200, 'b': 40, 't': 100, 'r': 200}, legend={'x': 0, 'y': 1}, hovermode='closest' ) } )
Whoa! A whole paragraph in Python! Don’t worry. It’s not difficult to understand. Let’s go over it piece by piece:
哇! Python的整个段落! 不用担心 不难理解。 让我们一步一步地研究它:
The dcc.Graph
has an id
argument which is used to reference the graph in the future for deleting or overlaying or any other purposes.
dcc.Graph
有一个id
参数,该参数将来用于引用图形以进行删除或覆盖或任何其他目的。
The figure
argument is the same as the one used in plotly.py. It takes in two arguments, data
and layout
.
figure
参数与plotly.py中使用的参数相同。 它接受两个参数, data
和layout
。
In data
we can specify which columns of the dataframe to plot on which axis. We can also specify the mode, for example: marker and then the properties of marker such as width and line (meaning border).
在data
我们可以指定要在哪个轴上绘制数据框的哪些列。 我们还可以指定模式,例如: 标记 ,然后指定标记的属性,例如宽度和线条 (意味着边框)。
In layout
we define the axes labels, legend position, graph margins (left, top, bottom, right) and much more.
在layout
我们定义了轴标签,图例位置,图形边距(左,上,下,右)等等。
This isn’t it. These graphs are interactive and can be manipulated by user inputs.
不是吗 这些图是交互式的 ,可以通过用户输入进行操作。
Ok, so let’s go build some cool DashApps this summer!
好的,让我们今年夏天开始构建一些很棒的DashApps!
Stay tuned for my next posts. This is not my first time coding or making an app, but it’s my first article on Medium! I think claps and recommendations will motivate me :)
请继续关注我的下一篇文章。 这不是我第一次编写或开发应用程序,但这是我在Medium上的第一篇文章! 我认为拍手和建议会激励我:)
Don’t hesitate to contact me via email: anujp5678[at]gmail[dot]com
不要犹豫,通过电子邮件与我联系:anujp5678 [at] gmail [dot] com
Or connect with me on LinkedIn https://www.linkedin.com/in/anuj-pahade/
或通过LinkedIn https://www.linkedin.com/in/anuj-pahade/与我联系
Keep dashing and happy coding!
继续使用破破烂烂的编码!
翻译自: https://www.freecodecamp.org/news/this-quick-intro-to-dash-will-get-you-to-hello-world-in-under-5-minutes-86f8ae22ca27/