我正在尝试使用 D3 创建词云。为此,我正在修改 Jason Davis 的代码:https://github.com/jasondavies/d3-cloud/blob/master/examples/simple.html
我想更改代码,以便不使用单词数组,而是可以链接到包含大量文本的 .txt 或 .csv 文件。
我尝试使用 d3.text() 和 d3.csv() 方法,但我做错了。由于两者 方法调用 URL,我使用数据 URL 生成器 ( http://dataurl.net/#dataurlmaker ) 将文本文件转换为 URL。然后我更改了代码并插入了数据 url,如下所示:
var fill = d3.scale.category20();
var text = d3.text(data:text/plain;base64,RGVsbCwgdGhl....continued....more...URLdata)
d3.layout.cloud().size([300, 300])
.words(text.map(function(d) {
return {text: d, size: 10 + Math.random() * 90};
}))
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
我尝试的第二个选项是将文本插入到 html 中的脚本标记中,然后在 JS 代码中引用它,如下所示:
<!DOCTYPE html>
<script src="../lib/d3/d3.js"></script>
<script id="text" type="text/plain">Dell, the company, has...more..text...</script>
<script src="../d3.layout.cloud.js"></script>
<body>
<script>
var fill = d3.scale.category20();
var text = d3.select("#text");
d3.layout.cloud().size([300, 300])
.words(text.map(function(d) {
return {text: d, size: 10 + Math.random() * 90};
}))
etc........
有人可以帮我想出一种读取 .txt 或 .csv 文件的方法吗? 谢谢!
最佳答案
更新:
你能看到这个吗?
http://bl.ocks.org/8bb2b55d2c5cf5667b01
熟悉工作 d3 和 .csv 文件的一种方法 是查看来自 Scott Murray's 的代码示例github 上的 d3 书。 (第 12 章是您可以复习的地方。) https://github.com/alignedleft/d3-book/tree/master/chapter_12
无论如何,我已经使用了修改后版本的 us-cities.csv Jason Davies 的 github 示例。
希望这对您有所帮助。
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3 CSV</title>
</head>
<body>
<script src="d3.v3.js"></script>
<script src="cloudlayout.js"></script>
<script type="text/javascript">
var fill = d3.scale.category20();
var cityData = [],
width = 500,
height = 500;
d3.csv("us-cities.csv", function(data) {
// build the list of city names
data.forEach( function (d) {
cityData.push(d.place);
});
d3.layout.cloud().size([500, 500])
.words(cityData.map(function(d) {
return {text: d, size: 10 + Math.random() * 90};
}))
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
});
function draw(words) {
d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform", "translate(150,150)")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
</script>
</body>
</html>
关于javascript - 来自外部 .csv 或 .txt 文件的 d3.js 云?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793859/