D3条形图示例不在本地工作

问题描述 投票:9回答:3

我是D3的新手,想看看一个例子如何在本地工作。我将条形图代码复制并粘贴到名为index.html的本地文件中,并复制到data.tsv上。出于某种原因,当我在浏览器上打开文件时,绝对没有任何东西出现!我尝试将脚本src更改为“d3 / d3.v3.min.js”,因为这是我下载的d3所在的文件夹。但是,这也不起作用。对于我尝试的每个例子,我还没有成功查看D3示例。帮助将不胜感激!

index.html代码如下:

<meta charset="utf-8">
<style>

body {
  font: 10px sans-serif;
}

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

.bar {
fill: steelblue;
}

.x.axis path {
 display: none;
}

</style>
<body>
<script src="d3/d3.v3.min.js"></script>
<script>

var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var formatPercent = d3.format(".0%");

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
   .range([height, 0]);

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

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

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 + ")");

d3.tsv("data.tsv", type, function(error, data) {
 x.domain(data.map(function(d) { return d.letter; }));
 y.domain([0, d3.max(data, function(d) { return d.frequency; })]);

  svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

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

  svg.selectAll(".bar")
  .data(data)
  .enter().append("rect")
  .attr("class", "bar")
  .attr("x", function(d) { return x(d.letter); })
  .attr("width", x.rangeBand())
  .attr("y", function(d) { return y(d.frequency); })
  .attr("height", function(d) { return height - y(d.frequency); });

});

function type(d) {
d.frequency = +d.frequency;
 return d;
}

</script>

data.tsv采用以下格式:字母频率A .08167 B .01492 C .02780 D .04253 E .12702 F .02288 G .02022 H .06094 I .06973

javascript html d3.js local
3个回答
16
投票

d3.tsv方法对数据进行AJAX请求。在大多数浏览器中,由于Same Origin Policy,这在本地不起作用,file:///通常禁止对> python -m SimpleHTTPServer 网址的AJAX请求。

要获得使用本地运行的AJAX的示例,您需要一个本地Web服务器。如果你有Python,那就跑了

> python -m http.server 9000

从您的文件目录中的命令行将执行它。

如果您使用的是python 3

http-server

如果您更喜欢node.js,请尝试使用http://plnkr.co/


1
投票

作为替代方案,我在Lars Kotthoff尝试使用.tsv / .csv文件时自己建议,您可以直接为此目的工作:

jsonp-d3-experiment

这使您可以使用您喜欢的所有.json / .tsv / .csv文件,并与人们共享以进行协作。您可以匿名或非匿名地执行此操作,重要的是您不会丢失当时生成的plunker的HTTP地址。

需要注意的一件事是:您不能像在FTP服务器上那样直接上传文件,但您应该:

  1. 点击“新文件”
  2. 键入代码中引用的.csv / .tsv / .json文件的名称(包括扩展名)
  3. 按原样复制并粘贴此文件中包含的代码。
  4. 如果需要,请不要忘记更新.css / .js的名称,以便与index.html的名称匹配

0
投票

如前所述,您最有可能在d3库中遇到与XHR的CORS问题,以便外部资源解析JSON数据。

但是,这是另一种解决方案:将JSONP和Express / Node.js与jQuery函数结合使用,以启动JSON的客户端请求,而不是使用d3函数的原始包装器。

必须删除原始的d3.json包装器并使用请求中的数据填充邻接图。首先克隆或下载node server.js并使用server.js启动服务器。当然,您需要全局安装Node.js,从Node Packaged Modules(npm)开始。将程序复制到子目录中。

将您的JSON数据放在jsonp-d3-experiment目录中并修改// Return data from callback server.get('/example', function(req, res) { // Read the JSON data and send to JSONP response readJSON('example.json', function (e, json) { if (e) { throw e; } res.jsonp(json); }); }); 以将请求路由到您的数据:

$.getJSON

下面是我为共生矩阵修改的代码。我将整个脚本移动到d3.json并完全删除了<script> $.getJSON("http://localhost:8080/example?callback=?", function(result){ miserables = result; var margin = { top: 80, right: 0, bottom: 10, left: 80 }, width = 720, height = 720; var x = d3.scale.ordinal().rangeBands([0, width]), z = d3.scale.linear().domain([0, 4]).clamp(true), c = d3.scale.category10().domain(d3.range(10)); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .style("margin-left", -margin.left + "px") .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var matrix = [], nodes = miserables.nodes, n = nodes.length; // Compute index per node. nodes.forEach(function(node, i) { node.index = i; node.count = 0; matrix[i] = d3.range(n).map(function(j) { return { x: j, y: i, z: 0 }; }); }); // Convert links to matrix; count character occurrences. miserables.links.forEach(function(link) { matrix[link.source][link.target].z += link.value; matrix[link.target][link.source].z += link.value; matrix[link.source][link.source].z += link.value; matrix[link.target][link.target].z += link.value; nodes[link.source].count += link.value; nodes[link.target].count += link.value; }); // Precompute the orders. var orders = { name: d3.range(n).sort(function(a, b) { return d3.ascending(nodes[a].name, nodes[b].name); }), count: d3.range(n).sort(function(a, b) { return nodes[b].count - nodes[a].count; }), group: d3.range(n).sort(function(a, b) { return nodes[b].group - nodes[a].group; }) }; // The default sort order. x.domain(orders.name); svg.append("rect") .attr("class", "background") .attr("width", width) .attr("height", height); var row = svg.selectAll(".row") .data(matrix) .enter().append("g") .attr("class", "row") .attr("transform", function(d, i) { return "translate(0," + x(i) + ")"; }) .each(row); row.append("line") .attr("x2", width); row.append("text") .attr("x", -6) .attr("y", x.rangeBand() / 2) .attr("dy", ".32em") .attr("text-anchor", "end") .text(function(d, i) { return nodes[i].name; }); var column = svg.selectAll(".column") .data(matrix) .enter().append("g") .attr("class", "column") .attr("transform", function(d, i) { return "translate(" + x(i) + ")rotate(-90)"; }); column.append("line") .attr("x1", -width); column.append("text") .attr("x", 6) .attr("y", x.rangeBand() / 2) .attr("dy", ".32em") .attr("text-anchor", "start") .text(function(d, i) { return nodes[i].name; }); function row(row) { var cell = d3.select(this).selectAll(".cell") .data(row.filter(function(d) { return d.z; })) .enter().append("rect") .attr("class", "cell") .attr("x", function(d) { return x(d.x); }) .attr("width", x.rangeBand()) .attr("height", x.rangeBand()) .style("fill-opacity", function(d) { return z(d.z); }) .style("fill", function(d) { return nodes[d.x].group == nodes[d.y].group ? c(nodes[d.x].group) : null; }) .on("mouseover", mouseover) .on("mouseout", mouseout); } function mouseover(p) { d3.selectAll(".row text").classed("active", function(d, i) { return i == p.y; }); d3.selectAll(".column text").classed("active", function(d, i) { return i == p.x; }); } function mouseout() { d3.selectAll("text").classed("active", false); } d3.select("#order").on("change", function() { clearTimeout(timeout); order(this.value); }); function order(value) { x.domain(orders[value]); var t = svg.transition().duration(2500); t.selectAll(".row") .delay(function(d, i) { return x(i) * 4; }) .attr("transform", function(d, i) { return "translate(0," + x(i) + ")"; }) .selectAll(".cell") .delay(function(d) { return x(d.x) * 4; }) .attr("x", function(d) { return x(d.x); }); t.selectAll(".column") .delay(function(d, i) { return x(i) * 4; }) .attr("transform", function(d, i) { return "translate(" + x(i) + ")rotate(-90)"; }); } var timeout = setTimeout(function() { order("group"); d3.select("#order").property("selectedIndex", 2).node().focus(); }, 5000); }); </script> 函数。

result

请注意,现在JSON数据位于miserables中,因此最简单的方法是将其分配给qazxswpoi。

注意:此解决方案需要jQuery。

现在,您应该可以在本地打开并呈现所有d3可视化,而无需将它们托管在服务器上 - 只需在浏览器中直接从本地文件系统打开它们即可。

HTH!

© www.soinside.com 2019 - 2024. All rights reserved.