D3轴tick
如何具有背景颜色?
这样做的一种野蛮方式是在每个rect
中添加g.tick
元素并在其上加fill
,但由于{{1} rect
,因此很难实现}必须与tick
..
以下是Mike Bostock的basic ticks example(和another的图表)
我拍了一张截图并标记了(红色边框)我希望刻度线有背景颜色:
有没有人知道在Ticks上有任何理智的背景色? 感谢
答案 0 :(得分:5)
另一种选择是制作这样的过滤器:
one
并勾选添加过滤器:
var filter = svg.append("defs").append("filter")
.attr("x", "0")
.attr("y", "0")
.attr("width", "1")
.attr("height", "1")
.attr("id", "background")//id of the filter
filter.append("feFlood")
.attr("flood-color", "red");
filter.append("feComposite")
.attr("in", "SourceGraphic");
工作代码here
答案 1 :(得分:3)
我不会这么快就放弃你的rect
想法。它实现起来非常简单,允许您根据需要调整“背景”的大小。以下是3个额外像素的外观:
d3.selectAll(".tick").each(function(d,i){
var tick = d3.select(this),
text = tick.select('text'),
bBox = text.node().getBBox();
tick.insert('rect', ':first-child')
.attr('x', bBox.x - 3)
.attr('y', bBox.y - 3)
.attr('height', bBox.height + 6)
.attr('width', bBox.width + 6)
.style('fill', d3.schemeCategory20[i % 20]);
});
完整示例:
<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="500"></svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 0, bottom: 20, left: 0},
width = svg.attr("width") - margin.left - margin.right,
height = svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scalePoint()
.domain([0, 1, 2])
.range([0, width])
.padding(1);
var y = d3.scaleLinear()
.domain([-1e6, 2e6])
.range([height, 0]);
g.append("g")
.attr("transform", "translate(" + x(0) + ",0)")
.attr("class", "axis")
.call(d3.axisLeft(y)
.ticks(20, "s"));
g.append("g")
.attr("transform", "translate(" + x(1) + ",0)")
.attr("class", "axis")
.call(d3.axisLeft(y)
.ticks(20)
.tickFormat(d3.format(".0s")));
g.append("g")
.attr("transform", "translate(" + x(2) + ",0)")
.attr("class", "axis")
.call(d3.axisLeft(y)
.ticks(20)
.tickFormat(d3.formatPrefix(".1", 1e6)));
d3.selectAll(".tick").each(function(d,i){
var tick = d3.select(this),
text = tick.select('text'),
bBox = text.node().getBBox();
tick.insert('rect', ':first-child')
.attr('x', bBox.x - 3)
.attr('y', bBox.y - 3)
.attr('height', bBox.height + 6)
.attr('width', bBox.width + 6)
.style('fill', d3.schemeCategory20[i % 20]);
});
</script>
答案 2 :(得分:2)
带填充的SVG文本背景颜色
<svg width="200" height="200">
<defs>
<filter x="-0.5" y="-0.5" width="2" height="2" id="solid">
<feFlood flood-color="#BDBDBD"></feFlood>
<feComposite in="SourceGraphic"></feComposite></filter>
</defs>
<text x="50" y="50" font-size="13" fill="#fff" filter="url(#solid)">7%</text>
</svg>
&#13;