我正在完成一个条形图,我遇到了一个奇怪的问题:第一个栏显示不正确。我有两个图表和两个相应的tsv
文件。显示密歇根州图表时,即使其数据对象属性d.Injured
等于2,第一个图标也不会显示。d3js:为什么第一个酒吧的数据显示不正确?
对于俄亥俄州图表,与第一个数据对象关联的所有属性都不是有效字符串/数字,因此图表挑选了1969
作为日期,即使它不在数据中。不幸的是,由于400 Bad Request
,我无法复制Plunkr上的代码。我已经包含了下面的js和数据示例,希望这个错误可能很明显。
全码:http://plnkr.co/edit/B0z0cyZRHfiVelGx6pnO?p=preview
d3.select('input[type=button]').on("click",function(){
country = document.getElementById("state").value;
d3.tsv(country + " Shootings.tsv",function(d,i){
d.Date = parser(d.Date);
d.Killed = +d.Killed;
d.Injured = +d.Injured;
return d;
}, function(error,data){
if (error){throw error};
console.log(data);
data.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(a.Date) - new Date(b.Date);
});
//Visualization
var readTime = d3.timeFormat("%Y-%m");
x.domain(data.map(function(d){return readTime(d.Date)}));
y.domain([0,d3.max(data, function(d){return d.Injured})]);
//Create axes
var updateXaxis = xaxis
.attr("class","xaxis")
.attr("transform","translate(0," + height + ")")
.call(d3.axisBottom(x));
var updateYaxis = yaxis
.attr("class","yaxis")
.call(d3.axisLeft(y).ticks(5));
//Create bars
var newState = g.selectAll(".bars")
.data(data,function(d){console.log(d); return d});
// the first bound data was: Object {State: "", School: undefined, Date: null, Killed: NaN, Injured: NaN…}
var StateWithContent = newState.enter().append("rect")
.attr("class","bars")
.attr("width", x.bandwidth())
.attr("x",function(d){return x(readTime(d.Date))})
.attr("height",function(d){return height - y(d.Injured)})
.attr("y",function(d){return y(d.Injured)});
console.log(newState.exit())
newState.exit().remove();
});
});
</script>
</body>
俄亥俄州Shootings.tsv
State School Date Killed Injured
Ohio Linden-McKinley High School 2016-10 0 2
Ohio Madison Jr/Sr High School 2016-2 0 4
Ohio Charles F. Brush High School 2014-2 0 0
Ohio LaSalle High School 2013-4 0 1
Ohio Chardon High School 2012-2 3 6
Ohio SuccessTech Academy 2007-10 1 4
Ohio Wickliffe Middle school 1994-11 1 5
密歇根Shootings.tsv
State School Date Killed Injured
Michigan Davidson Middle School 2013-02 1 0
Michigan Osborn High School 2013-01 0 1
Michigan Northern High School 2011-12 0 1
Michigan Mumford High School 2010-09 0 2
Michigan Henry Ford High School 2008-10 1 3
Michigan Buell Elementary School 2000-02 1 0
Michigan Chelsea High School 1993-12 1 2
俄亥俄图
您的数据似乎有空格而不是制表符,但我不确定这是否发生在您转移到堆栈溢出时。你也没有给我们你的日期分析器的方法。当我运行数据解析部分时,它似乎回来了正确的数据。 – user3432422
我的解析器方法是'var parser = d3.timeParse(“%Y-%m”);'是的,所有的数据似乎是正确的,直到'.enter'和'exit'选择。我摆脱了NaN值,但第一个酒吧总是以与第一个显示的图表相同的高度结束。我注意到第一个栏并没有包含在'exit'选项中,但是我不知道如何解决这个问题 – st4rgut