【发布时间】:2015-08-03 07:02:04
【问题描述】:
我正在使用与下面相同的图表。我想将 x 轴标题,即常规、高级、预算稍低于即顶部填充或边距。给它一些样式,比如给背景颜色和改变文本颜色。我尝试使用填充,但它没有按预期工作。我也想隐藏价格层/渠道
http://dimplejs.org/examples_viewer.html?id=bars_vertical_grouped
【问题讨论】:
我正在使用与下面相同的图表。我想将 x 轴标题,即常规、高级、预算稍低于即顶部填充或边距。给它一些样式,比如给背景颜色和改变文本颜色。我尝试使用填充,但它没有按预期工作。我也想隐藏价格层/渠道
http://dimplejs.org/examples_viewer.html?id=bars_vertical_grouped
【问题讨论】:
这些是 SVG 文本元素,因此没有顶部填充或边距。不过,您可以通过增加 y 属性将它们向下移动一点,在调用 chart.draw 方法后运行以下命令会将标签向下移动 5 个像素:
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
.attr("y", function (d) {
// Get the y property of the current shape and add 5 pixels
return parseFloat(d3.select(this).attr("y")) + 5;
});
要更改文本颜色,您需要使用填充属性(同样是 svg 文本):
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
.style("fill", "red");
给文本的背景上色不是那么简单,在 SVG 中实际上没有这样的事情,但是你可以在文本后面插入一个矩形,然后用它做你喜欢的事情:
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
// Iterate each shape matching the selector above (all the x axis labels)
.each(function () {
// Select the shape in the current iteration
var shape = d3.select(this);
// Get the bounds of the text (accounting for font-size, alignment etc)
var bounds = shape.node().getBBox();
// Get the parent group (this the target for the rectangle to make sure all its transformations etc are applied)
var parent = d3.select(this.parentNode);
// This is just the number of extra pixels to add around each edge as the bounding box is tight fitting.
var padding = 2;
// Insert a rectangle before the text element in the DOM (SVG z-position is entirely determined by DOM position)
parent.insert("rect", ".dimple-custom-axis-label")
// Set the bounds using the bounding box +- padding
.attr("x", bounds.x - padding)
.attr("y", bounds.y - padding)
.attr("width", bounds.width + 2 * padding)
.attr("height", bounds.height + 2 * padding)
// Do whatever styling you want - or set a class and use CSS.
.style("fill", "pink");
});
这三个语句都可以链接在一起,所以最终的代码看起来有点像这样:
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
.attr("y", function (d) { return parseFloat(d3.select(this).attr("y")) + 5; })
.style("fill", "red")
.each(function () {
var shape = d3.select(this);
var bounds = shape.node().getBBox();
var parent = d3.select(this.parentNode);
var padding = 2;
parent.insert("rect", ".dimple-custom-axis-label")
.attr("x", bounds.x - padding)
.attr("y", bounds.y - padding)
.attr("width", bounds.width + 2 * padding)
.attr("height", bounds.height + 2 * padding)
.style("fill", "pink");
});
仅供参考,dimple-custom-axis-label 类是在最近发布的dimple 中添加的,因此请确保您使用的是最新版本。否则你将不得不找到一个替代选择器
【讨论】: