<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.d3-tip {
line-height: 1;
font-weight: bold;
padding: 12px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 2px;
}
/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}
/* Style northward tooltips differently */
.d3-tip.n:after {
margin: -1px 0 0 0;
top: 100%;
left: 0;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script>
var margin = {top: 100, right: 20, bottom: 30, left: 50},
width = 500;
height = 200;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .5);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "<strong>Cases:</strong> <span style='color:red'>" + d.cases + "</span>";
})
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 + ")");
svg.call(tip);
d3.json("Cutaneous_leishmaniasis.json", function(error, data) {
x.domain(data.map(function(d) { return d.year;}));
y.domain([0, d3.max(data, function(d) { return d.cases; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("transform", "0")
.attr("x", 10)
.attr("dx", ".71em")
.style("text-anchor", "right")
.text("Afghanistan");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 100)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Deaths");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.year); })
.attr("width", x.rangeBand(1))
.attr("y", function(d) { return y(d.deaths); })
.attr("height", function(d) { return height - y(d.cases); })
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
});
function type(d) {
d.deaths = +d.deaths;
return d;
}
</script>
上面的代码将使用我拥有的JSON数据创建条形图,但是y轴数据不是从y轴的0值开始,我不知道是什么原因导致这种情况。是否有任何属性或方法导致图中出现此问题?
以下是我创建的条形图的屏幕截图,并且y轴不会从y轴的值0开始。 http://i.stack.imgur.com/igQts.jpg
答案 0 :(得分:1)
您使用d3.json
作为d.cases
变量在y
函数的开头设置了域名,但在设置高度时,使用d.deaths.
{{1}功能设置为使用y
数字作为它的比例,所以你需要选择一个,我认为。