django和d3.tsv,不工作

时间:2017-02-12 17:08:11

标签: javascript django d3.js

我现在完全糊涂了,它只是不起作用!

我的django观点:

def data_tsv(request):
    event = Event.objects.get(pk=request.GET.get('epk'))
    occurrences = event.occurrences.all()

    response = HttpResponse(content_type='text/tsv')
    response['Content-Disposition'] = 'filename="data.tsv"'

    for occ in occurrences:
        response.write('%s  %s\n' % (occ.timestamp, occ.counter))

    return response

我的js:

var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,

g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var parseTime = d3.timeParse("%d-%b-%y");

var x = d3.scaleTime().rangeRound([0, width]);

var y = d3.scaleLinear().rangeRound([height, 0]);

var line = d3.line()
    .x(function (d) {
        return x(d.date);
    })
    .y(function (d) {
        return y(d.close);
    });

d3.tsv("{% url 'data_tsv' %}?epk={{ event.id }}", function (d) {
    d.date = parseTime(d.date);
    d.close = +d.close;
    return d;
}, function (error, data) {
    if (error) throw error;

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

    g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x))
        .select(".domain")
        .remove();

    g.append("g")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("fill", "#000")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("text-anchor", "end")
        .text("Price ($)");

    g.append("path")
        .datum(data)
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-linejoin", "round")
        .attr("stroke-linecap", "round")
        .attr("stroke-width", 1.5)
        .attr("d", line);
 });

我正在

enter image description here

我的data.tsv看起来像这样:

2017-02-12 14:07:14.566084  1
2017-02-12 14:07:35.718406  1
2017-02-12 17:12:14.380712  1
2017-02-12 17:23:40.195434  1
2017-02-12 17:51:52.866287  1

我正在尝试运行此代码:https://bl.ocks.org/mbostock/3883245

任何帮助都非常感谢

编辑:改变马克的说法后:我现在正在接受

enter image description here

两个日志行来自:

console.log(d.date);
console.log(parseTime(d.date));

1 个答案:

答案 0 :(得分:1)

假设您的int文件包含tsvdate标题,并且django的文件下载正在运行,那么您的问题就是日期解析。

这一行:

close

是“02-Feb-17”之类的日期,但你有“2017-02-12 17:51:52.866287”,它接近:

var parseTime = d3.timeParse("%d-%b-%y");

但是这会变得有点棘手,因为JavaScript日期只有毫秒精度,你必须敲掉微秒:

var parseTime = d3.timeParse("%Y-%m-%d %H:%M:%S.%L");

正在运行代码here