3

Is there a simple way to place rounded corners just on the top of the Bar(s) in a D3 Vertical Bar Chart? I've been playing around with .attr("rx", 3) and that seems to affect all four corners of a Bar.

Rob
  • 14,746
  • 28
  • 47
  • 65
user1104028
  • 381
  • 7
  • 18

1 Answers1

4

You cannot specify which corners you want to make round in SVG: rx will affect all 4 corners.

The only solution is using a path for simulating a rectangle. This function returns a path with top corners round:

function rectangle(x, y, width, height, radius){
    return "M" + (x + radius) + "," + y + "h" + (width - 2*radius) 
    + "a" + radius + "," + radius + " 0 0 1 " + radius + "," + radius + "v" + 
    (height - 2*radius) + "v" + radius + "h" + -radius + "h" + 
    (2*radius - width) + "h" + -radius + "v" + -radius + "v" + 
    (2*radius - height) + "a" + radius + "," + radius + " 0 0 1 " 
    + radius + "," + -radius + "z";
};

Here is a demo snippet showing a "bar chart" with those paths, with a radius (the rx equivalent here) of 5px:

function rectangle(x, y, width, height, radius){
 return "M" + (x + radius) + "," + y + "h" + (width - 2*radius) + "a" + radius + "," + radius + " 0 0 1 " + radius + "," + radius + "v" + (height - 2*radius) + "v" + radius + "h" + -radius + "h" + (2*radius - width) + "h" + -radius + "v" + -radius + "v" + (2*radius - height) + "a" + radius + "," + radius + " 0 0 1 " + radius + "," + -radius + "z";
};

var data = [40, 50, 30, 40, 90, 54, 20, 35, 60, 42];

var svg = d3.select("body")
 .append("svg")
 .attr("width", 400)
 .attr("height", 120);
 
var rects = svg.selectAll(".paths").data(data).enter().append("path");
rects.attr("d", function(d,i){ return rectangle(10+40*i,100-d,20,d,5)});

var texts = svg.selectAll(".text").data("ABCDEFGHIJ".split("")).enter().append("text").attr("y",114).attr("x", function(d,i){return 16+40*i}).text(function(d){return d});
path {
  fill:teal;
}

text {
  fill:darkslategray;
  font-size: 12px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>

PS: I didn't write that function, it was based on these answers by M. Bostock and R. Longson.

Community
  • 1
  • 1
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171