d3.js数据已导入,但条形图未显示



我试图使用csv文件中的数据制作条形图。它有两列:year/running_total

tbody> <<tr>
year running_total
18841
196950710

现在你正在传递一个所有年份的数组

x.domain(data.map(function(d) { return d.year; }));

您需要将数据中年份的最小/最大值传递给x.domain()-您可以使用d3.extent来完成此操作:

x.domain(d3.extent(data, function(d) {return d.year}));

下面是一个例子:

// define the dimensions and margins for the graph
var margin = {top: 10, right: 10, bottom: 10, left: 10},
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom,
padding = 0.5;
// define function to parse time in years format
var parseTime = d3.timeParse("%Y")
// create scales x & y for X and Y axis and set their ranges
var x = d3.scaleTime().range ([margin.left+padding, width-padding]);
var y = d3.scaleLinear().range ([height, 0]);

// append svg element to the body of the page
// set dimensions and position of the svg element
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
/* Create bar plot using data from csv */
var data = [];
var rt = 10;
for (let i=1850; i<1875; i++) {
data.push({
"year": parseTime(i),
"running_total": rt
});
rt += Math.floor(Math.random() * 100) + 1;
}

// set the domains of X and Y scales based on data
//x.domain(data.map(function(d) { return d.year; }));
x.domain(d3.extent(data, function(d) {return d.year}));
y.domain([0, d3.max(data, function(d){return d.running_total; })]);
// Add bars to svg - create new elements based on your data
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", function(d) { return x(d.year); })
.attr("y", function(d) { return y(d.running_total); })
.attr("width", width/data.length - padding)
.attr("height", function(d) { return height - y( d.running_total); })
.attr("fill", "steelblue");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

相关内容

  • 没有找到相关文章

最新更新