javascript - D3 Bar Graph example not working locally -
i new d3, , wanted see how illustration work locally. copied , pasted bar graph code local file called index.html, , copied on data.tsv. reason, absolutely nil showing when open file on browser! tried changing script src "d3/d3.v3.min.js" because folder d3 downloaded in. however, not work either. every illustration have tried have yet view d3 example. help appreciated!
the index.html code follows:
<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) { homecoming d.letter; })); y.domain([0, d3.max(data, function(d) { homecoming 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) { homecoming x(d.letter); }) .attr("width", x.rangeband()) .attr("y", function(d) { homecoming y(d.frequency); }) .attr("height", function(d) { homecoming height - y(d.frequency); }); }); function type(d) { d.frequency = +d.frequency; homecoming d; } </script> and data.tsv in next format: letter frequency .08167 b .01492 c .02780 d .04253 e .12702 f .02288 g .02022 h .06094 .06973
the d3.tsv method makes ajax request data. on browsers, won't work locally due same origin policy, prohibits ajax requests file:/// urls.
to illustration uses ajax running locally, you'll need local webserver. if have python, running
> python -m simplehttpserver from command line in directory files it. if prefer node.js, seek http-server.
javascript html d3.js local
No comments:
Post a Comment