问题
I'm trying to build a d3 bar chart, but due to a sneaky designer, I need rounded corners on the top-left and -right of each bar. I think I'm getting somewhere, but I could use a bit of help to push it over the line.
Still very much on the uphill curve learning about d3 and svg, so I hope I haven't missed anything obvious.
I have successfully made this work using the rects (commented out section), but there's a flaw, probably in how I'm drawing the paths. The anonymous functions I'm passing as arguments into the topRoundedRect function (e.g. function(datum, index) { return x(index); }) are not being evaluated before being appended to the d attribute of the path, and I don't understand why. So I end up getting an error like this:
Error: Problem parsing d="Mfunction (datum, index) { return x(index); }3,function (datum) { return height - y(datum); }h34a3,3 0 0 1 3,3vNaNh-40vNaNa3,3 0 0 1 3,-3z"
Any advice you can offer would be fantastic. Code below.
var data = [60.45,60.45,89.54,120.34,106.45,127.43];
var barWidth = 40;
var width = (barWidth + 10) * data.length;
var height = 500;
var x = d3.scale.linear().domain([0, data.length]).range([0, width]);
var y = d3.scale.linear().domain([0, d3.max(data, function(datum) { return datum; })]).
rangeRound([0, height]);
// add the canvas to the DOM
var barDemo = d3.select("body").
append("svg").
attr("width", width).
attr("height", height);
function topRoundedRect(x, y, width, height, radius) {
return "M" + (x + radius) + "," + y
+ "h" + (width - (radius * 2))
+ "a" + radius + "," + radius + " 0 0 1 " + radius + "," + radius
+ "v" + (height - radius)
+ "h" + (0-width)
+ "v" + (0-(height-radius))
+ "a" + radius + "," + radius + " 0 0 1 " + radius + "," + -radius
+ "z";
}
/*
barDemo.selectAll("rect").
data(data).
enter().
append("svg:rect").
attr("x", function(datum, index) { return x(index); }).
attr("y", function(datum) { return height - y(datum); }).
attr("height", function(datum) { return y(datum); }).
attr("width", barWidth).
attr("fill", "url(#barGradient)"); */
barDemo.selectAll("path").
data(data).
enter().append("path").
attr("d", topRoundedRect(
function(datum, index) { return x(index); },
function(datum) { return height - y(datum); },
barWidth,
function(datum) { return y(datum); },
3))
.style("fill","#ffcc00")
.style("stroke","none");
回答1:
The argument for your attribute should be a function that takes the datum and index as parameters. Try:
attr("d", function(datum, index) {
return topRoundedRect( x(index),
height - y(datum),
barWidth,
y(datum),
3);
})
来源:https://stackoverflow.com/questions/12914228/d3-custom-bar-chart-bars-using-svg-paths-instead-of-rects