Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active July 5, 2018 19:17
Show Gist options
  • Save mbostock/3305937 to your computer and use it in GitHub Desktop.
Save mbostock/3305937 to your computer and use it in GitHub Desktop.
d3.tsv
license: gpl-3.0

D3 2.10 adds support for tab-separated values via d3.tsv. Similar to the previous d3.csv method, this makes it easy to load and parse TSV files.

d3.tsv("data.tsv", function(data) {
  console.log(data[0].x);
});
x y
5 90
25 30
45 50
65 55
85 25
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.point {
fill: steelblue;
stroke: #000;
}
</style>
<body>
<script src="//d3js.org/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 x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
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", function(error, data) {
if (error) throw error;
// Coerce the data to numbers.
data.forEach(function(d) {
d.x = +d.x;
d.y = +d.y;
});
// Compute the scales’ domains.
x.domain(d3.extent(data, function(d) { return d.x; })).nice();
y.domain(d3.extent(data, function(d) { return d.y; })).nice();
// Add the x-axis.
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis().scale(x).orient("bottom"));
// Add the y-axis.
svg.append("g")
.attr("class", "y axis")
.call(d3.svg.axis().scale(y).orient("left"));
// Add the points!
svg.selectAll(".point")
.data(data)
.enter().append("circle")
.attr("class", "point")
.attr("r", 4.5)
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); });
});
</script>
@liufly
Copy link

liufly commented Nov 12, 2013

I believe this may help
http://stackoverflow.com/a/18973278

I had the exact same issue and solved it by using the answer mentioned above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment