D3 条形图示例在本地不起作用
D3 Bar Graph example not working locally
我对 D3 很陌生,想看看一个示例在本地如何工作。我将条形图代码复制并粘贴到一个名为 index.html 的本地文件中,并复制了 data.tsv。出于某种原因,当我在浏览器上打开文件时,绝对没有显示任何内容!我尝试将脚本 src 更改为"d3/d3.v3.min.js",因为这是我下载的 d3 所在的文件夹。但是,这也不起作用。对于我尝试的每个示例,我尚未成功查看 D3 示例。帮助将不胜感激!
索引.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乙.01492C.02780编号:04253E .12702传真 .02288G .02022H .06094I .06973
d3.tsv
方法发出 AJAX 数据请求。在大多数浏览器上,由于同源策略,这在本地不起作用,该策略通常禁止 AJAX 请求file:///
URL。
要获取使用本地运行的 AJAX 的示例,您需要一个本地 Web 服务器。如果你有 Python,运行
> python -m SimpleHTTPServer
从带有文件的目录中的命令行就可以了。
如果您使用的是 Python 3
> python -m http.server 9000
如果您更喜欢node.js,请尝试http-server。
作为替代方案,Lars Kotthoff 在尝试使用 .tsv/.csv 文件时建议我自己,您可以直接为此目的工作:
http://plnkr.co/
这使您能够处理您喜欢的所有 .json/.tsv/.csv 文件,并与人们共享它们以进行协作。您可以匿名或不匿名执行此操作,重要的是您不会丢失 plunker 当时生成的 HTTP 地址。
需要注意的一件事:您不能像在FTP服务器上那样直接上传文件,而应该:
- 点击"新文件"
- 输入您的.csv的名称/.tsv/.json代码中引用的文件(包括扩展名)
- 复制并按原样粘贴此文件中包含的代码。
- 别忘了如果需要,更新您的.css/.js的名称,以便与您的索引.html
如前所述,您很可能在 d3 库中遇到 XHR 的 CORS 问题,以便外部资源解析 JSON 数据。
但是,这是另一种解决方案:将 JSONP 和 Express/Node 结合使用.js与 jQuery 函数结合使用来启动 JSON 的客户端请求,而不是对 d3 函数使用原始包装器。
必须删除原始的 d3.json 包装器,并使用请求中的数据填充邻接关系图。首先克隆或下载 jsonp-d3-experiment,然后使用 node server.js
启动服务器。当然,您需要全局安装 Node.js,从节点打包模块 (npm) 开始。将程序复制到子目录中。
将 JSON 数据放入 jsonp-d3-experiment 目录中,并修改server.js
以将请求路由到您的数据:
// 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>
请注意,现在 JSON 数据在 result
中,所以最简单的方法是将其分配给 miserables
。
注意:此解决方案需要 jQuery。
现在,您应该能够本地打开和渲染所有 d3 可视化,而无需将它们托管在服务器上 - 只需直接从本地文件系统在浏览器中打开它们即可。
哼!
- d3.js组条形图不起作用
- 为什么d3.js饼图转换不起作用
- jQuery Animate 在创建图库滑块时不起作用
- 图层删除(图像);在 Kinetic.js 中不起作用
- D3js 饼图单击事件不起作用
- 直接从代码笔复制的圆环图代码不起作用
- D3中的排序条形图不起作用
- 谷歌运动图不起作用
- 鼠标点击在我的html5柱状图中不起作用
- onclick() jQuery/JavaScript 显示饼图的按钮不起作用
- d3js散点图自动更新不起作用
- 高位图向下钻取不起作用
- 堆积条形图到分组条形图过渡不起作用
- 通过 json 更新的 Canvasjs 柱形图不起作用
- 工具提示不起作用谷歌饼图
- 无法加载高图.js和高图.js(地图.js不起作用)
- D3 条形图示例在本地不起作用
- D3js响应堆叠条形图-其他主题解决方案不起作用
- 堆叠条形图's悬停不起作用
- D3 堆积条形图在支流中有效,但在其他地方不起作用