我开始可视化我用熊猫提取的数据。我已经查看了d3.js教程和示例,并决定编写一个简单的条形图,但是渲染的内容与csv格式的数据不一致。 y轴上的标签不出现,数据也不出现在y轴上。 x轴上的一个字段甚至没有数据可视化。
< script type = "text/javascript" >
var canvas = document.querySelector("canvas");
var context = canvas.getContext("2d");
// Set the dimensions of the canvas / graph
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 50
},
width = canvas.width - margin.left - margin.right,
height = canvas.height - margin.top - margin.bottom;
var x = d3.scaleBand()
.rangeRound([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
context.translate(margin.left, margin.top);
d3.csv("data/ecci.csv", function(data) {
data.forEach(function(d) {
d.NGNAmountCashBalance = +d.NGNAmountCashBalance;
d.Region = d.Region;
});
console.log(data[5]);
x.domain(data.map(function(d) {
return d.Region;
}));
y.domain([0, d3.max(data, function(d) {
return d.NGNAmountCashBalance;
})]);
context.beginPath();
x.domain().forEach(function(d) {
context.moveTo(x(d) + x.bandwidth() / 2, height);
context.lineTo(x(d) + x.bandwidth() / 2, height + 6);
});
context.strokeStyle = "black";
context.stroke();
context.textAlign = "center";
context.textBaseline = "top";
x.domain().forEach(function(d) {
context.fillText(d, x(d) + x.bandwidth() / 2, height + 6);
});
context.beginPath();
context.strokeStyle = "black";
context.stroke();
context.textAlign = "right";
context.textBaseline = "middle";
context.beginPath();
context.moveTo(-6.5, 0 + 0.5);
context.lineTo(0.5, 0 + 0.5);
context.lineTo(0.5, height + 0.5);
context.lineTo(-6.5, height + 0.5);
context.strokeStyle = "black";
context.stroke();
context.save();
context.rotate(-Math.PI / 2);
context.textAlign = "right";
context.textBaseline = "top";
context.font = "light 13px verdana";
context.fillText("ACCIS Chart", -10, 10);
context.restore();
context.fillStyle = "steelblue";
data.forEach(function(d) {
context.fillRect(x(d.Region), y(d.NGNAmountCashBalance), x.bandwidth(), height - y(d.NGNAmountCashBalance));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.5/d3.min.js"></script>
<canvas width="660" height="500"></canvas>
JSFiddle - https://jsfiddle.net/gbade/o11d5tb8/
拜托,我到底错过了什么?
答案 0 :(得分:2)
很难回答这个没有查看您的数据,但假设它看起来像这样(至少):
canvas
您的图表适用于我除之外的部分:
数据也不出现在y轴上
那是因为你没有画出y轴。由于您正在使用 var yTickCount = 5,
yTicks = y.ticks(yTickCount);
context.beginPath();
yTicks.forEach(function(d) {
context.moveTo(0, y(d) + 0.5);
context.lineTo(-6, y(d) + 0.5);
});
context.strokeStyle = "black";
context.stroke();
context.textAlign = "right";
context.textBaseline = "middle";
yTicks.forEach(function(d) {
context.fillText(d, -9, y(d));
});
,因此它看起来像:
var boolean = new Boolean(true);
console.log(boolean === true);
这里有一个完整的running example。