Flask + Altair

Example of a Flask + Altair Dashboard

Flask + Altair 仪表板示例

Let's consider a simple example where we set up a Flask route to display an Altair plot:
让我们考虑一个简单的示例,其中我们设置了一个 Flask 路由来显示 Altair 图:

from flask import Flask, render_template
import altair as alt
import pandas as pd

app = Flask(__name__)

@app.route('/')
def index():
    # Sample data
    data = pd.DataFrame({
        'x': ['A', 'B', 'C', 'D', 'E'],
        'y': [5, 7, 9, 11, 13]
    })

    # Create an Altair chart
    chart = alt.Chart(data).mark_bar().encode(
        x='x',
        y='y'
    ).interactive()

    # Convert the Altair chart to a JSON format
    chart_json = chart.to_json()

    return render_template('altair.html', chart=chart_json)

if __name__ == "__main__":
    app.run(debug=True)

Here's a sample altair.html what might look like:
下面是一个示例 altair.html ,如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Altair Visualization with Flask</title>
    <!-- Import the Vega-Embed library -->
    <script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega-lite@5"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
</head>
<body>
    <div id="vis"></div>
    
    <script>
        // Parse the Altair JSON chart data passed from Flask
        var chartData = {{ chart|safe }};

        // Use Vega-Embed to render the chart
        vegaEmbed('#vis', chartData);
    </script>
</body>
</html>

A few important points to highlight:
需要强调的几个要点:

  1. The altair.html file imports the necessary Vega and Vega-Embed JavaScript libraries, which are needed to render Altair visualizations.
    该文件 altair.html 导入渲染 Altair 可视化所需的 Vega 和 Vega-Embed JavaScript 库。

  2. The JSON chart data from the Flask application is passed to the template using the {{ chart|safe }} syntax. The |safe filter ensures that the JSON is correctly parsed as raw JSON rather than as a string.
    Flask 应用程序中的 JSON 图表数据使用以下 {{ chart|safe }} 语法传递到模板。筛选器 |safe 可确保将 JSON 正确解析为原始 JSON,而不是字符串。

  3. The vegaEmbed function from the Vega-Embed library is used to render the visualization inside the div with the id vis.
    Vega-Embed 库中的 vegaEmbed 函数用于在 id div vis 中呈现可视化效果。

To run the application, ensure this altair.html file is saved inside the templates directory of your Flask project. When you visit the root route (/), you should see a bar chart rendered in the browser. This is just a simple example to illustrate the integration. Real-world applications can involve more intricate designs, interactions, and data manipulations.
若要运行应用程序,请确保此 altair.html 文件保存在 templates Flask 项目的目录中。当您访问根路由 ( / ) 时,您应该会在浏览器中看到呈现的条形图。这只是一个简单的示例来说明集成。实际应用程序可能涉及更复杂的设计、交互和数据操作。


Altair, with its expressive grammar, combined with Flask's robustness, can be a potent combination for creating insightful, interactive web-based dashboards. However, be prepared to dip your toes into the world of web technologies to truly harness their combined power.
Altair 具有富有表现力的语法,结合 Flask 的稳健性,可以成为创建富有洞察力的交互式基于 Web 的仪表板的有力组合。但是,请准备好涉足网络技术世界,以真正利用它们的综合力量。
转自:https://book.datascience.appliedhealthinformatics.com/docs/Ch4/flask-altair

posted @ 2023-12-18 22:03  MasonLee  阅读(18)  评论(0编辑  收藏  举报