我是D3新手,并通过条形图示例。我想要确保条和标签的高度是一致的。现在它取决于回来的条目数量。所以,如果有1,那就有一个巨大的斑点。如果有10则则条形较慢。这是代码和链接。
https://plnkr.co/edit/CZEyIaOxItoWZXSQkqjH?p=preview
的index.html
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
margin: 15px;
background-color: #F1F3F3
}
.bar {
fill: #6F257F;
}
.axis path,
.axis line {
fill: none;
stroke: #D4D8DA;
stroke-width: 1px;
shape-rendering: crispEdges;
}
.x path {
display: none;
}
.toolTip {
position: absolute;
display: none;
min-width: 80px;
height: auto;
background: none repeat scroll 0 0 #ffffff;
border: 1px solid #6F257F;
padding: 14px;
text-align: center;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 80},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var tooltip = d3.select("body").append("div").attr("class", "toolTip");
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleBand().range([height, 0]);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("data.json", function(error, data) {
if (error) throw error;
data.sort(function(a, b) { return a.value - b.value; });
x.domain([0, d3.max(data, function(d) { return d.value; })]);
y.domain(data.map(function(d) { return d.area; })).padding(0.1);
g.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).ticks(5).tickFormat(function(d) { return parseInt(d / 1000); }).tickSizeInner([-height]));
g.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(y));
g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", 0)
.attr("height", y.bandwidth())
.attr("y", function(d) { return y(d.area); })
.attr("width", function(d) { return x(d.value); })
.on("mousemove", function(d){
tooltip
.style("left", d3.event.pageX - 50 + "px")
.style("top", d3.event.pageY - 70 + "px")
.style("display", "inline-block")
.html((d.area) + "<br>" + "£" + (d.value));
})
.on("mouseout", function(d){ tooltip.style("display", "none");});
});
</script>
data.json
[
{"area": "central ", "value": 18000},
{"area": "Riverside ", "value": 17000},
{"area": "Picton ", "value": 80000},
{"area": "Everton ", "value": 55000},
{"area": "Kensington ", "value": 100000},
{"area": "Kirkdale", "value": 50000},
{"area": "Evertons ", "value": 5000},
{"area": "Kensingtons ", "value": 100000},
{"area": "Everton ", "value": 55000},
{"area": "Kensington ", "value": 100000},
{"area": "Kirkdale", "value": 50000}
]
谢谢!
答案 0 :(得分:2)
如果我正确理解您的问题,您需要确保每个条形图总是具有相同的高度(以像素为单位),无论条形数量如何。
如果这是正确的,请动态设置范围。例如:
var barSize = 40;
y.range([barSize*data.length, 0]);
以下是包含完整数据数组的plunker:https://plnkr.co/edit/zNOMcQob6fSFkEYclyzS?p=preview
现在,为了比较,只有三个数据元素的相同代码:https://plnkr.co/edit/KciR2eheLLIOS1SHUM7i?p=preview
PS:您有area
属性的重复名称。这并不适用于有序规模。
PPS:一个好主意是根据数据长度设置SVG高度。