1 回答
TA贡献1834条经验 获得超8个赞
一个简单的条件运算符就足够了:
.attr("y", function(d) {
return h - (d.Value * 10) - (d.Value * 10 < 40 ? 40 : 0);
})
作为旁注,您应该使用 D3 音阶。在您的特定数据集中,值可以很容易地映射到 SVG 坐标,但几乎从来都不是这样。
这是带有该更改的代码:
var w = 750;
var h = 300;
var barPadding = 2;
var dataset2 = [{
"category": "A",
"Value": 18,
"URLimage": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Baseball.svg/520px-Baseball.svg.png"
},
{
"category": "B",
"Value": 15,
"URLimage": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Baseball.svg/520px-Baseball.svg.png"
},
{
"category": "C",
"Value": 13,
"URLimage": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Baseball.svg/520px-Baseball.svg.png"
},
{
"category": "D",
"Value": 2,
"URLimage": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Baseball.svg/520px-Baseball.svg.png"
},
{
"category": "E",
"Value": 12,
"URLimage": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Baseball.svg/520px-Baseball.svg.png"
},
{
"category": "F",
"Value": 15,
"URLimage": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Baseball.svg/520px-Baseball.svg.png"
},
{
"category": "G",
"Value": 20,
"URLimage": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Baseball.svg/520px-Baseball.svg.png"
},
{
"category": "H",
"Value": 25,
"URLimage": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Baseball.svg/520px-Baseball.svg.png"
},
{
"category": "H",
"Value": 30,
"URLimage": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Baseball.svg/520px-Baseball.svg.png"
}
]
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(dataset2)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset2.length);
})
.attr("y", function(d) {
return h - (d.Value * 10);
})
.attr("width", w / dataset2.length - barPadding)
.attr("height", function(d) {
return d.Value * 10;
})
svg.selectAll(".images")
.data(dataset2)
.enter().append("svg:image")
.attr("x", function(d, i) {
return i * (w / dataset2.length) + 18;
})
.attr("y", function(d) {
return h - (d.Value * 10) - (d.Value * 10 < 40 ? 40 : 0);
})
.attr("width", 40)
.attr("height", 40)
.attr("xlink:href", function(d, i) {
return dataset2[i].URLimage
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
添加回答
举报