【发布时间】:2020-06-22 15:33:55
【问题描述】:
我一直致力于创建一个简单的 D3 条形图可视化,但由于某种原因,条形(矩形)没有出现在我的可视化中。可视化使用 .csv 作为用于可视化的原始数据。我可以开始使用的图表的唯一部分是轴,但即使我在绘制轴时更改函数调用的顺序,它们也会消失。
我尝试使用.selectAll("rect") 函数调用以及.join("rect") 和.append("rect") 函数调用,但似乎没有任何效果。我写的代码如下。我尝试了许多在线资源来确定 rect 对象无法显示的原因。
我正在使用 d3.js API 版本 5。
<script>
var margin = { top: 30, right: 30, bottom: 30, left: 30 },
width = 1000 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
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 + ')');
//defines the x-axis which is based on a numerical format
var xScale = d3.scaleLinear()
.rangeRound([0, width]);
//defines the y-axis which is based on a numerical format
var yScale = d3.scaleLinear()
.rangeRound([height, 0]);
d3.csv("http://raw.githubusercontent.com/naija-queen/Raw-Data/master/crashing.csv").then(function (data) {
//sets the domain of the x-axis
xScale.domain([0, d3.max(data, function(d){
return (Number(d.episode));
})])
//sets the domain of the y-axis
yScale.domain([0, d3.max(data, function(d){
return (Number(d.percent));
})])
//draws the x-axis
svg.append('g')
.attr("transform", "translate(0," + height + ")")
//.ticks() command allows you to define how many ticks you want to see in the visualization
.call(d3.axisBottom(xScale).ticks(16))
//draws the y-axis
svg.append("g")
//for some reason moving arround the function call below makes the y-axis disappear
.call(d3.axisLeft(yScale))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("text-anchor", "end")
.text("Percent Watched");
//parts of a bar chart
svg.append('bar')
.attr("fill", "lightskyblue")
.selectAll("rect")
.data(data)
.join("rect")
// d => is basically function(d){}
.attr("x", d => xScale(Number(d.episode)))
.attr("y", d => yScale(Number(d.percent)))
.attr("width", 20)
.attr("height", d => yScale(0) - yScale(Number(d.percent)));
});
</script>
我是 D3 的新手,所以请尽可能解释一下你的答案。
【问题讨论】:
标签: javascript d3.js svg bar-chart data-visualization