修改凹坑布局分组图表

时间:2015-08-03 07:02:05

标签: d3.js dimple.js

我使用的图表如下。我想推动x轴标题,即常规,高级,预算稍微低一点,即顶部填充或边距。给它一些造型,比如给出背景颜色和改变文字颜色。我尝试使用填充,它不能按预期工作。我想隐藏Price Tier / Channel也

http://dimplejs.org/examples_viewer.html?id=bars_vertical_grouped

1 个答案:

答案 0 :(得分:0)

这些是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版本中添加了dimple-custom-axis-label类,因此请确保您使用的是最新版本。否则,您必须找到替代选择器