Bar chart using d3.js, pandas and flask

I am trying to display a bar chart in an HTML page using d3.js and the JSON data is coming from Flask. Below is the code for the flas:

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()

      

I am connecting to sqlite3 db and forming a pandas framework and manipulating it, which should eventually be plotted. The JSON data passed to d3.js looks like this: 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"}}'

      

Below is 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>

      

Below is the new.js file with the d3.js code:

// 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); });

});

      

When navigating to localhost: / 5000, no graph appears. I don't know what the missing piece is.

+3


source to share


2 answers


Passed data as below:

data = json.dumps(df_list)
return render_template('display.html',data=data)

      



And then display the graph from the JSON data.

<script>
var chartData = {{ data | safe }};
console.log(chartData);

      

+3


source


The correct way is to have 2 routes, one serving as JSON data and the other that returns a template. Something like:

from flask import jsonify

@app.route("/data")
def get_data():
    // all that stuff you did to create the dataset
    return jsonify(data)

@app.route("/chart")
def chart_page():
     return render_template("some_template.html")

      



And then in your JS diagram, just make the call d3.json

as you do above.

+1


source







All Articles