我正在尝试使用d3.js在HTML页面上呈现条形图,而JSON数据来自Flask。以下是烧瓶代码:
import sqlite3
import pandas as pd
from flask import *
app = Flask(__name__)
@app.route("/")
def show_graph():
connection = sqlite3.connect('recruit.db')
query = "select * from customer"
df_customer = pd.read_sql(query, connection)
df_fb_usage = df_customer.loc[:,['race_code','facebook_user_rank']]
df_fb_usage.facebook_user_rank = df_fb_usage.facebook_user_rank.astype(int)
plot_df = df_fb_usage.groupby('race_code').agg({'facebook_user_rank':'mean'})
plot_df = plot_df.reset_index()
query = "select * from race"
df_race = pd.read_sql(query,connection)
df_race.columns = ['race_code','value']
Plot_df_new = plot_df.merge(df_race,right_index=True,left_index=True,how='outer')
Plot_df_new = Plot_df_new.drop(['race_code_x','race_code_y'],axis=1)
Plot_df_new.columns = ['ethinicity','facebook_user_rank']
data = Plot_df_new.to_json()
return render_template('display.html',data)
if __name__ == "__main__":
app.run()
我正在连接到 sqlite3 db 并形成一个pandas数据帧并对其进行操作,最终需要进行绘制。传递给d3.js的JSON数据如下所示:它是 dtype str 。
'{"ethinicity":{"0":9.4029749831,"1":10.7621770122,"2":12.2134703196,"3":11.2112214312,"4":9.1842105263,"5":12.3614457831,"6":14.659334126,"7":7.5,"8":10.6363044469},"facebook_user_rank":{"0":"Asian","1":"Black","2":"Chinese","3":"Hispanic","4":"American Indian","5":"Japanese","6":"Other","7":"Portuguese","8":"White"}}'
以下是 display.HTML
<!DOCTYPE html>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="{{url_for('static',filename='new.js')}}"></script>
.bar{
fill: steelblue;
}
.bar:hover{
fill: brown;
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</body>
以下是带有d3.js代码的 new.js 文件:
// set the dimensions of the canvas
var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// set the ranges
var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
var y = d3.scale.linear().range([height, 0]);
// define the axis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
// add the SVG element
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// load the data
d3.json("/data", function(error, data) { //right way to refer to tje JSON data passed from flask??
data.forEach(function(d) {
d.ethinicity = d.ethinicity;
d.facebook_user_rank = +d.facebook_user_rank;
});
// scale the range of the data
x.domain(data.map(function(d) { return d.ethinicity; }));
y.domain([0, d3.max(data, function(d) { return d.facebook_user_rank; })]);
// add axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)" );
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 5)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("facebook_user_rank");
// Add bar chart
svg.selectAll("bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.ethinicity); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.facebook_user_rank); })
.attr("height", function(d) { return height - y(d.facebook_user_rank); });
});
在转到 localhost:/ 5000 时,图表似乎不会出现。不知道遗失的是什么。
答案 0 :(得分:4)
传递数据如下:
data = json.dumps(df_list)
return render_template('display.html',data=data)
然后从JSON数据中渲染图形。
<script>
var chartData = {{ data | safe }};
console.log(chartData);
答案 1 :(得分:1)
正确的方法是有2条路线,一条用于以JSON格式提供数据,另一条用于返回模板。类似的东西:
d3.json
然后在你的JS图表中,只需像上面那样进行{{1}}调用。