如何在条形图上制作垂直角? [英] How to make Vertical corners on a Bar Chart?

查看:84
本文介绍了如何在条形图上制作垂直角?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在D3垂直条形图中,是否有一种简单的方法就可以在圆条的顶部放置圆角?我一直在玩.attr("rx",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.

推荐答案

您无法指定要在SVG中打圆的角:rx将影响所有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";
};

下面是一个演示片段,其中显示了带有这些路径的条形图",半径为5px(此处等于rx):

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:我没有编写该函数,它基于

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

这篇关于如何在条形图上制作垂直角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆