【发布时间】:2021-02-12 21:51:15
【问题描述】:
我试图使用 csv 文件中的数据制作条形图。它有两列:year / running_total
| year | running_total |
|---|---|
| 1884 | 1 |
| ... | ... |
| 1969 | 50710 |
| ... | ... |
<!DOCTYPE html>
<head>
<style>
<!-- define CSS rules -->
</style>
</head>
<body>
<script src="lib/d3/d3.min.js"></script>
<script src="lib/d3-dsv/d3-dsv.min.js"></script>
<script src="lib/d3-fetch/d3-fetch.min.js"></script>
<script>
// define the dimensions and margins for the graph
var margin = {top: 20, right: 80, bottom: 20, left: 80},
width = 960 - margin.left - margin.right,
height = 500 - 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 + ")");
// Get the data
var pathToCsv = "q3.csv"; // path to csv
d3.dsv(",", pathToCsv, function (d) {
return {
// format data attributes if required
year: parseTime(d.year),
running_total: +d.running_total
}
}).then(function (data) {
console.log(data); // you should see the data in your browser's developer tools console
/* Create bar plot using data from csv */
// set the domains of X and Y scales based on data
x.domain(data.map(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");
// Add the X Axis
//svg.append()
// Add the text label for X Axis
//svg.append()
// Add the Y Axis
//svg.append()
// Add the text label for Y axis
//svg.append()
}).catch(function (error) {
console.log(error);
});
</script>
</body>
我可以看到正确导入的数据,但我不确定为什么没有图表显示。
【问题讨论】:
-
是否有任何错误弹出?
-
@rguttersohn 没有。这是让我很困惑的部分
标签: javascript html d3.js