这是 this question 的后续问题.
如何得到背景中代表100%且平行于Y轴的条纹灰度?
代码:
var data = [
{
"age": "Under 18",
"value": "582.13",
"color": "#B3DA29"
},
{
"age": "18 - 22",
"value": "583.98",
"color": "#78C0F2"
},
{
"age": "23 - 34",
"value": "603.00",
"color": "#9B58B5"
},
{
"age": "35 - 60",
"value": "607.70",
"color": "#E54C3C"
},
{
"age": "60 - Above",
"value": "610.00",
"color": "#F2519D"
}
];
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 400 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
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")
.ticks(10, "%");
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 + ")");
x.domain(data.map(function(d) { return d.age; }));
y.domain([0, d3.max(data, function(d) { return d.value; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.age); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return d.color; })
.attr("rx", 10)
.attr("ry", 10)
.on("mouseover", function(d) {
tooltip.transition().duration(200).style("opacity", .9);
tooltip.html("Count: " + d.value)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
tooltip.transition().duration(500).style("opacity", 0);
});
最佳答案
这是它的工作原理。
更新了 fiddle
.
svg.selectAll(".backgound-bar") .data(data) .enter() .append("rect") .attr("class", "background-bar") .attr("x", function(d) { return x(d.age); }) .attr("width", x.rangeBand()) .attr("y", function(d) { return y(800); }) .attr("height", height) .style("fill", "#ddd") .attr("rx", 10) .attr("ry", 10)
用 background-bar
类创建了一个 svg
元素。
并且 x
和 y
与您之前定义的相同。
但是条形的高度被赋予定义的 height
变量。
希望这有帮助:)
关于javascript - 如何使条形图的条纹灰色背景类似于 100%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21823226/