Flask + Plotly仪表盘

来源:https://blog.heptanalytics.com/2018/08/07/flask-plotly-dashboard/

原始代码:https://github.com/yvonnegitau/flask-Dashboard

上周我有3天的时间来设计一个可视化仪表盘。我的后端选择是flask(我们是不可分割的),但我不得不选择最简单的绘图包。我的选择是在plotly, dash和bokeh之间。看着bokeh文档,我发现它是直接向前的。然而,我发现的一个缺点是:使用分类数据。尽管所有其他包都与分类数据无缝地工作,但当涉及到bokeh时,必须进行一些修改。这让我开始寻找另一种选择。其他的 plotly 或者它的仪表盘 Dash。现在似乎很明显,人们会选择Dash,但我喜欢控制前端(我不害怕与css、js和html正面交锋)。这就是为什么我决定和plotly一起去。

一、安装依赖关系

pip install flask

pip install plotly

pip install pandas

pip install numpy

二、创建flask应用程序

应用程序的结构如下所示。静态文件夹将用于存储所有css、js和images文件。如果您正在使用任何 bootstrap模板,这是您将存储文件的地方。所有html文件都将在template文件夹中。

python文件将具有以下初始代码。

from flask import Flask

app = Flask(__name__)

@app.route('/')

def index():

    return 'Hello World!'

if __name__ == '__main__':

    app.run()

运行该文件时,您将在url http://localhost:5000/中看到Hello World。

然后,我们将创建一个名为index.html的html并将其保存在模板文件夹中。该文件将首先有一个基本代码:

<!DOCTYPE html>

<html>

<head lang="en">

    <meta charset="UTF-8">

    <title>My First Dashboard</title>

</head>

<body>

<div class="container">

    <div class="row">

        <div class="col-md-6">

            <div class="chart" id="bargraph">

            </div>

        </div>

    </div>

</div>

</body>

</html>

然后,我们将更改python文件以呈现html文件。注意,我们必须在imports中添加render模板。

from flask import Flask, render_template #this has changed

app = Flask(__name__)

@app.route('/')

def index():

    return render_template('index.html') #this has changed

if __name__ == '__main__':

    app.run()

三、第一张图

我们将绘制一个柱状图,如图所示。我们将创建一个返回绘图的函数。现在,我爱上了这个包。渲染图的简单性。然而,要发现这一点并不容易。这就是我决定分享这个的原因。

首先让我们导入所有的依赖:

import plotly

import plotly.graph_objs as go

import pandas as pd

import numpy as np

import json

create plot函数将具有以下代码。我们将创建我们自己的示例dataframe,如果您有一个文件,您将用dataframe替换它:

def create_plot():

    N = 40

    x = np.linspace(0, 1, N)

    y = np.random.randn(N)

    df = pd.DataFrame({'x': x, 'y': y}) # creating a sample dataframe

    data = [

        go.Bar(

            x=df['x'], # assign x as the dataframe column 'x'

            y=df['y']

        )

    ]

    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)

    return graphJSON

json变量是用html文件在index函数上呈现的内容。我们将这样做:

@app.route('/')

def index():

    bar = create_plot()

    return render_template('index.html', plot=bar)

现在在html文件中,我们将使用变量来绘图。我们将不得不添加plotly和d3 javascript来显示这个情节。使用jinja2变量绘制图形的代码如下所示:

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>

<div class="chart" id="bargraph">

    <script>

        var graphs = {{plot | safe}};

        Plotly.plot('bargraph',graphs,{});

    </script>

</div>

请注意,div类必须为要显示的绘图绘制图表。当您运行python文件并重新加载页面时,您应该会看到一个bar图:



您已经在html上添加了一个绘图。这是基础。我们可以继续设计。我不会在这篇博客中提到这一点。我想要完成的是添加ajax调用。

四、使用ajax调用创建绘图

我花了一段时间才弄明白。让我们添加一个下拉菜单,我们将使用它来更改绘图的类型。

<div class="col-xs-3">

    <label> Choose the plot type....</label>

    <select class="form-control" id ='first_cat'>

        <option value="Bar">Bar</option>

        <option value="Scatter">Scatter</option>

    </select>

</div>

现在,让我们创建一个名为plots.js的javascript,它将在更改时具有ajax功能。我们将返回绘图的json变量。

$('#first_cat').on('change',function(){

    $.ajax({

        url: "/bar",

        type: "GET",

        contentType: 'application/json;charset=UTF-8',

        data: {

            'selected': document.getElementById('first_cat').value

        },

        dataType:"json",

        success: function (data) {

            Plotly.newPlot('bargraph', data );

        }

    });

})

ajax函数将从下拉列表中获取所选的变量,并将其传递给flask中的函数,然后返回绘图。Flask代码如下:

@app.route('/bar', methods=['GET', 'POST'])

def change_features():

    feature = request.args['selected']

    graphJSON= create_plot(feature)

    return graphJSON

我必须编辑create plot函数以适应对plot的选择。新代码如下:

def create_plot(feature):

    if feature == 'Bar':

        N = 40

        x = np.linspace(0, 1, N)

        y = np.random.randn(N)

        df = pd.DataFrame({'x': x, 'y': y}) # creating a sample dataframe

        data = [

            go.Bar(

                x=df['x'], # assign x as the dataframe column 'x'

                y=df['y']

            )

        ]

    else:

        N = 1000

        random_x = np.random.randn(N)

        random_y = np.random.randn(N)

        # Create a trace

        data = [go.Scatter(

            x = random_x,

            y = random_y,

            mode = 'markers'

        )]

    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)

    return graphJSON

不要忘记在你的index.html和plot.js中添加jquery javascript

<script src="{{ url_for('static', filename='js/jquery-1.11.1.min.js') }}"></script>

<script src="{{ url_for('static', filename='js/plots.js') }}"></script>

通过这些更改,我们可以再次运行python文件。当我们选择散点绘图选项时,您应该能够看到绘图。


这样你就可以开始创建仪表盘了。


简单版本:

import plotly

import plotly.graph_objs as go

import pandas as pd

import numpy as np

import json

from flask import Flask, render_template #this has changed

app = Flask(__name__)

def create_plot():

    N = 40

    x = np.linspace(0, 1, N)

    y = np.random.randn(N)

    df = pd.DataFrame({'x': x, 'y': y}) # creating a sample dataframe

    data = [

        go.Bar(

            x=df['x'], # assign x as the dataframe column 'x'

            y=df['y']

        )

    ]

    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)

    return graphJSON

@app.route('/')

def index():

    bar = create_plot()

    print 111111

    return render_template('index.html', plot=bar)

if __name__ == '__main__':

    app.run()


所使用的网页:


<!DOCTYPE html>

<html>

<head lang="en">

    <meta charset="UTF-8">

    <title>My First Dashboard</title>

    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>

</head>

<body>

<div class="container">

    <div class="row">

        <div class="col-md-6">

            <div class="chart" id="bargraph">

    <script>

var graphs = {{plot | safe}};

Plotly.plot('bargraph',graphs,{});

    </script>

            </div>

        </div>

    </div>

</div>

</body>

</html>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • # -*- coding: utf-8 -*- from __future__ import division f...
    小豆角lch阅读 1,483评论 0 1
  • 受到numpy100题的启发,我们制作了pandas50题。 Pandas 是基于 NumPy 的一种数据处理工具...
    91160e77b9d6阅读 1,102评论 0 0
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,554评论 0 13
  • matplotlib是PYTHON绘图的基础库,是模仿matlab绘图工具开发的一个开源库。 PYTHON其它第三...
    卅清阅读 753评论 0 0
  • 人们向来重视结果,忽略过程。原因很简单:结果往往是很容易感受,而过程却被包裹在每天不经意的生活中。比如:考试...
    虚王阅读 412评论 0 1