出于某种原因,我的酒吧(rects)画得非常宽 - 我认为是因为日期没有正确解析。这是代码
var fakeData= [
{"date":2013-10,"shortFig":10},
{"date":2013-11,"shortFig":-15},
{"date":2013-12,"shortFig":15},
{"date":2014-01,"shortFig":39},
{"date":2014-02,"shortFig":-38},
{"date":2014-03,"shortFig":33},
{"date":2014-04,"shortFig":-35},
{"date":2014-05,"shortFig":-2},
{"date":2014-06,"shortFig":-39},
{"date":2014-07,"shortFig":-46},
{"date":2014-08,"shortFig":23},
{"date":2014-09,"shortFig":45}
]
..这个数据变成了数据"在我的图表构建函数中,我尝试解析数据并构建x刻度和x轴:
// parse dates
var parseDate = d3.time.format("%Y–%m").parse;
thedata.forEach(function(d) {
var date = d.date.toString();
d.date = parseDate(date);
});
//The X scale
var xScale=d3.scale.ordinal()
.rangeRoundBands([0, width], .1)
.domain(thedata.map(function(d) { return d.date; }));
//With the X scale, set up the X axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickValues([thedata[0].date]);
//Call the X axis
baseGroup.append("g")
.attr("class", "xaxis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
baseGroup.selectAll("rect")
.data(thedata)
.enter()
.append("rect")
.attr("class", function(d){ if(d.shortFig >= 0){return "green3"}else{return "red3"} })
.attr({
"x": function(d) {return xScale(d.date);},
"y": function(d) {return yScale(Math.max(0, d.shortFig));}, //Return the number with the highest value
"height": function(d) {return Math.abs(yScale(d.shortFig) - yScale(0));}, //Return the absolute value of a number, so negative numbers will be positive
"width": xScale.rangeBand()
});
答案 0 :(得分:0)
只是一个错字,date
参数应该是字符串。经测试,它可以工作,只需替换fakeData
数组,就应该设置它。
var fakeData= [
{"date":"2013-10","shortFig":10},
{"date":"2013-11","shortFig":-15},
{"date":"2013-12","shortFig":15},
{"date":"2014-01","shortFig":39},
{"date":"2014-02","shortFig":-38},
{"date":"2014-03","shortFig":33},
{"date":"2014-04","shortFig":-35},
{"date":"2014-05","shortFig":-2},
{"date":"2014-06","shortFig":-39},
{"date":"2014-07","shortFig":-46},
{"date":"2014-08","shortFig":23},
{"date":"2014-09","shortFig":45}
];
var parseDate = d3.time.format("%Y-%m").parse;
fakeData.forEach(function(d){
console.log(parseDate(d.date));
});