/*给body添加大小*/body,
html{height:100%;
}
{padding:0;margin:0;
}.axis path,
.axis line{fill:none;stroke:black;shape-rendering:crispEdges;
}.axis text{font-family:sans-serif;font-size:11px;
}.MyRect{fill:palevioletred;
}.MyText{fill:black;text-anchor:middle;font-size:10px;
}
varwidth= 500;varheight= 500;varsvg=d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);varpadding={
left:30,
right:30,
top:20,
bottom:20};http://blog.sina.com.cn/s/blog_ad72a03a0102v1nx.html 含解释
d3.csv("../bardata.csv",function(error, data, i) {if(error) {
console.log(error);
}
console.log(data);vardatavalue=[]for(let i= 0; i
datavalue.push(data[i].value)
} //var xp = d3.scale.ordinal()
.domain(d3.range(dataset.length))
使用map来输入data数组中的字符
//.domain(data.map(function(d,i){
console.log(d.items)
//return d.items
//}))
//.rangeRoundBands([0,width-padding.left-padding.right]);
//var xp = d3.scale.ordinal()
//.domain(data.map(function(d){ return d.items;}))
//.rangeBands([0,width-padding.left-padding.right]);
//以上定义xp(即xscale)横坐标序数比例尺的方法都可以试一下,会有不同的体验
varxp=d3.scale.ordinal()
.domain(data.map(function(d) {returnd.items;
}))
.rangeRoundBands([0, width-padding.left-padding.right],0.1);varyp=d3.scale.linear()
.domain([0, d3.max(datavalue)])
.range([height-padding.top-padding.bottom,0])//反过来?为什么呢(之前似乎讲过哦0w0)
varxAxis=d3.svg.axis()
.scale(xp)
.orient("bottom");varyAxis=d3.svg.axis()
.scale(yp)
.orient("left");varrectPadding= 4;varrects=svg.selectAll(".MyRect")
.data(data)
.enter()
.append("rect")
.attr("class","MyRect")
.attr("transform","translate(" +padding.left+ "," +padding.top+ ")")
.attr("x",function(d, i) {returnxp(d.items);
})
.attr("y",function(d) {returnyp(d.value);
})
.attr("width", xp.rangeBand()-rectPadding)
.attr("height",function(d) {returnheight-padding.top-padding.bottom-yp(d.value);
})
.on("mouseover",function(d, i) {
d3.select(this)
.style("fill","aliceblue");
})
.on("mouseout",function(d, i) {
d3.select(this)
.style("fill","greenyellow");//使用style替换attr才会有交互的效果
});vartexts=svg.selectAll(".MyText")
.data(data)//害我出错的就是这儿了,我之前写的是.data(datavalue),datavalue又是哪儿来的呢?为什么引用错误,会导致tips的位置错乱呢?
.enter()
.append("text")
.attr("class","MyText")
.attr("transform","translate(" +padding.left+ "," +padding.top+ ")")
.attr("x",function(d) {returnxp(d.items);//上面问题的答案都在这儿,d=》data,数据的意思,那data是哪儿来的呢?当然是我们传进来的,那为什么data不会出错,而datavalue会错呢?
//是由于xp()是我们之前定义的序数比例尺,我们如果想要使用就必须传入适合的数据(包含x,y),如果只是传入datavalue就只有y值,而我们并没有将x传入。
})
.attr("y",function(d) {returnyp(d.value);
})
.attr("dx",function() {return(xp.rangeBand()-rectPadding)/ 2;
})
.attr("dy",function(d) {return 15;
})
.text(function(d) {returnd.value;
});
svg.append("g")
.attr("class","axis")
.attr("transform","translate(" +padding.left+ "," +(height-padding.bottom)+ ")")
.call(xAxis);
svg.append("g")
.attr("class","axis")
.attr("transform","translate(" +padding.left+ "," +padding.top+ ")")
.call(yAxis);
})