TypeError:undefined不是对象(评估'e.length')

时间:2017-05-16 06:15:30

标签: javascript d3.js ipython-notebook

我正在尝试在iPython中构建一个d3散点图,其中x轴为日期,这是我的代码:

from IPython.core.display import display, HTML
from string import Template
import pandas as pd
import json, random

HTML('<script src="lib/d3/d3.min.js"></script>')

x = [1,2,3]
y = ["1-May-12","2-May-12","3-May-12"]
data = []
for i in range(len(x)):
    data.append({'x': x[i], 'y': y[i]})

import pandas as pd
data_pd = pd.DataFrame(columns=['x', 'y'])
data_pd['x'] = x
data_pd['y'] = y
data_array_of_dicts = data_pd.to_dict(orient='records')

然后是css风格

css_text = '''
.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.dot {
  stroke: #000;
}
'''

和模板:

js_text_template = Template('''
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 720 - margin.left - margin.right,
    height = 375 - margin.top - margin.bottom;

// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;

// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var svg = d3.select("#$graphdiv").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 + ")");

var data = $python_data ;
  data.forEach(function(d) {
        d.date = parseDate(d.date);
        d.close = +d.close;

   });
    x.domain(d3.extent(data, function(d) { return d.date; }));
    y.domain([0, d3.max(data, function(d) { return d.close; })]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .append("text")
      .attr("class", "label")
      .attr("x", width)
      .attr("y", -6)
      .style("text-anchor", "end")
      .text("x axis");

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("class", "label")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("y axis")

  svg.selectAll(".dot")
      .data(data)
    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 3.5)

''')


html_template = Template('''
<style> $css_text </style>
<div id="graph-div"></div>
<script> $js_text </script>
''')
js_text = js_text_template.substitute({'python_data':     json.dumps(data_array_of_dicts),
                                   'graphdiv': 'graph-div'})
HTML(html_template.substitute({'css_text': css_text, 'js_text': js_text}))

但是,此代码返回此错误:

Javascript error adding output!
TypeError: undefined is not an object (evaluating 'e.length')
See your browser Javascript console for more details.

0 个答案:

没有答案