我正在尝试创建一个flask应用程序,以呈现从熊猫的CSV文件中读取的一些图表数据。在不知道自己在做什么的情况下,我从amcharts.com复制了this javascript chart并将其合并到下面的HTML文件中。 index.html
在我的烧瓶应用程序中,当我运行服务器时,AM图表可以通过浏览器正常运行,但是我不知道如何将自己的数据传递给Jinja,然后传递给前端。我知道AM图表必须显示虚拟数据,因为在Jinja中我没有做任何引用来引用它。任何提示都可以帮助(这里的学习曲线很深),而且我也不知道我应该解析Python app.py还是javascript中的数据。在app.py中,当读取CSV文件时,会在其中解析数据,但不知道其是否正确。
Index.html:
<<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
/body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
#chartdiv {
width: 100%;
height: 500px;
}
</style>
</head>
<body>
<div id="graphDiv"></div>
<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
<div id="chartdiv"></div>
<script>
// JINJA
var graphData = {{ data.chart_data | safe }}
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end
var chart = am4core.create("chartdiv", am4charts.XYChart);
var data = [];
var value = 50;
for(let i = 0; i < 300; i++){
let date = new Date();
date.setHours(0,0,0,0);
date.setDate(i);
value -= Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
data.push({date:date, value: value});
}
chart.data = data;
// Create axes
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.minGridDistance = 60;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
// Create series
var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = "value";
series.dataFields.dateX = "date";
series.tooltipText = "{value}"
series.tooltip.pointerOrientation = "vertical";
chart.cursor = new am4charts.XYCursor();
chart.cursor.snapToSeries = series;
chart.cursor.xAxis = dateAxis;
//chart.scrollbarY = new am4core.Scrollbar();
chart.scrollbarX = new am4core.Scrollbar();
</script>
</body>
</html>
app.py:
import json
from flask import Flask, render_template
import pandas as pd
app = Flask(__name__)
@app.route("/")
def index():
df = pd.read_csv('data.csv', index_col='Date', parse_dates=True)
chart_data = df.to_dict(orient='records')
chart_data = json.dumps(chart_data, indent=2)
data = {'chart_data': chart_data}
return render_template("index.html", data=data)
if __name__ == "__main__":
app.run(debug=True)