如何使用d3js在条形图上居中对齐文本标签

时间:2019-01-01 07:01:01

标签: javascript css d3.js svg

我有以下使用40%构建的条形图。我无法将条形标签的中心居中。例如。 var margin = { top: 10, right: 0, bottom: 58, left: 40 }; var width = 400 - margin.left - margin.right; var height = 400 - margin.top - margin.bottom; var barWidth = 40; var graph; var xScale; var yScale; var dataSet; dataSet = [{ desc: 'test1', val: 40 }, { desc: 'some dummy text here', val: 120 }]; xScale = d3.scaleBand() .domain(dataSet.map(function(d) { return d.desc; })) .range([0, width]); yScale = d3.scaleLinear() .range([height, 0]) .domain([0, 1.15 * d3.max(dataSet, function(d) { return d.val; })]); graph = d3.select("#graph") .append("svg") .attr("class", "bar-chart") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); graph.append("g") .attr("class", "x-scale") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(xScale)) .selectAll(".tick text") .call(wrap, xScale.bandwidth()); graph.append("g") .attr("class", "y-scale") .call(d3.axisLeft(yScale).tickPadding(10)); graph .append("g") .attr('class', 'graph-placeholder') .selectAll("rect") .data(dataSet) .enter() .append("rect") .attr("class", "bar1") .attr("height", height) .attr("width", barWidth) .attr('x', d => xScale(d.desc) + (xScale.bandwidth() - barWidth) / 2); graph .append("g") .attr('class', 'graph-main') .selectAll("bar1") .data(dataSet) .enter() .append("rect") .attr("class", "bar2") .attr('x', d => xScale(d.desc) + (xScale.bandwidth() - barWidth) / 2) .attr("y", function(d) { return yScale(d.val); }) .attr("height", function(d) { return height - yScale(d.val); }) .attr("width", barWidth); graph .append("g") .attr('class', 'bar-label') .selectAll("text") .data(dataSet) .enter() .append("text") .text(d => d.val+ '%') .attr("y", function(d) { return yScale(d.val) - 5; }).attr('x', function(d) { return xScale(d.desc) + ((xScale.bandwidth() - barWidth) / 2); }); function wrap(text, width) { text.each(function() { var text = d3.select(this), words = text.text().split(/\s+/).reverse(), word, line = [], lineNumber = 0, lineHeight = 1, y = text.attr("y"), dy = parseFloat(text.attr("dy")), tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em"); while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); if (tspan.node().getComputedTextLength() > width) { line.pop(); tspan.text(line.join(" ")); line = [word]; tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word); } } }); }没有与条居中对齐。

摘要:

.bar2 {
  fill: steelblue;
}

.bar1 {
  fill: #f2f2f2;
}

text {
  font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
  <div id="graph"></div>
</div>
#include <iostream>

#define MAXN 1000000009

using namespace std;

bool prime[MAXN] = {true};

int main()
{
    for (int p = 2; p * p <= MAXN; ++p)
        if (prime[p])
        {
            cout << p << "\n";

            for (int i = p * p; i <= MAXN; i += p)
                prime[i] = false;
        }

    return 0;
}

2 个答案:

答案 0 :(得分:0)

请勿使用硬编码的条形宽度。使用padding中的scaleBand

xScale = d3.scaleBand()
  .domain(dataSet.map(function(d) { return d.desc; }))
  .range([0, width])
  .padding(0.6);

要使文本居中,请设置以下属性

  .attr("text-anchor", "middle")

var margin = {
  top: 10,
  right: 0,
  bottom: 58,
  left: 40
};
var width = 400 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
//var barWidth = 40;

var graph;
var xScale;
var yScale;
var dataSet;

dataSet = [{
  desc: 'test1',
  val: 40
}, {
  desc: 'some dummy text here',
  val: 120
}];

xScale = d3.scaleBand()
  .domain(dataSet.map(function(d) { return d.desc; }))
  .range([0, width])
  .padding(0.6);

yScale = d3.scaleLinear()
  .range([height, 0])
  .domain([0, 1.15 * d3.max(dataSet, function(d) {
    return d.val;
  })]);

graph = d3.select("#graph")
  .append("svg")
  .attr("class", "bar-chart")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


graph.append("g")
  .attr("class", "x-scale")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(xScale))
  .selectAll(".tick text")
  .call(wrap, xScale.bandwidth());

graph.append("g")
  .attr("class", "y-scale")
  .call(d3.axisLeft(yScale).tickPadding(10));

graph
  .append("g")
  .attr('class', 'graph-placeholder')
  .selectAll(".bar1")
  .data(dataSet)
  .enter()
  .append("rect")
  .attr("class", "bar1")
  .attr("height", height)
  .attr("width", xScale.bandwidth())
  .attr('x', d => xScale(d.desc));

graph
  .append("g")
  .attr('class', 'graph-main')
  .selectAll(".bar2")
  .data(dataSet)
  .enter()
  .append("rect")
  .attr("class", "bar2")
  .attr('x', d => xScale(d.desc))
  .attr("y", function(d) { return yScale(d.val); })
  .attr("height", function(d) { return height - yScale(d.val); })
  .attr("width", xScale.bandwidth());


graph
  .append("g")
  .attr('class', 'bar-label')
  .selectAll("text")
  .data(dataSet)
  .enter()
  .append("text")
  .text(d => d.val+ '%')
  .attr("text-anchor", "middle")
  .attr("y", function(d) { return yScale(d.val) - 5; })
  .attr('x', function(d) { return xScale(d.desc) + xScale.bandwidth() / 2; });

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
      words = text.text().split(/\s+/).reverse(),
      word,
      line = [],
      lineNumber = 0,
      lineHeight = 1,
      y = text.attr("y"),
      dy = parseFloat(text.attr("dy")),
      tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}
.bar2 {
  fill: steelblue;
}

.bar1 {
  fill: #f2f2f2;
}

text {
  font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
  <div id="graph"></div>
</div>

答案 1 :(得分:0)

使用现有代码,您可以在栏的开头放置文本,对吗?

根据文本宽度稍稍修改代码(如我之前的answer中所述),

.attr('x', function(d) {
   return xScale(d.desc) + ((xScale.bandwidth() - barWidth) / 2) + (barWidth/2 - d3.select(this).node().getBBox().width/2);
});

这是带有修改后代码的片段

var margin = {
  top: 10,
  right: 0,
  bottom: 58,
  left: 40
};
var width = 400 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
var barWidth = 40;

var graph;
var xScale;
var yScale;
var dataSet;

dataSet = [{
  desc: 'test1',
  val: 40
}, {
  desc: 'some dummy text here',
  val: 120
}];

xScale = d3.scaleBand()
  .domain(dataSet.map(function(d) {
    return d.desc;
  }))
  .range([0, width]);

yScale = d3.scaleLinear()
  .range([height, 0])
  .domain([0, 1.15 * d3.max(dataSet, function(d) {
    return d.val;
  })]);

graph = d3.select("#graph")
  .append("svg")
  .attr("class", "bar-chart")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


graph.append("g")
  .attr("class", "x-scale")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(xScale))
  .selectAll(".tick text")
  .call(wrap, xScale.bandwidth());

graph.append("g")
  .attr("class", "y-scale")
  .call(d3.axisLeft(yScale).tickPadding(10));

graph
  .append("g")
  .attr('class', 'graph-placeholder')
  .selectAll("rect")
  .data(dataSet)
  .enter()
  .append("rect")
  .attr("class", "bar1")
  .attr("height", height)
  .attr("width", barWidth)
  .attr('x', d => xScale(d.desc) + (xScale.bandwidth() - barWidth) / 2);

graph
  .append("g")
  .attr('class', 'graph-main')
  .selectAll("bar1")
  .data(dataSet)
  .enter()
  .append("rect")
  .attr("class", "bar2")
  .attr('x', d => xScale(d.desc) + (xScale.bandwidth() - barWidth) / 2)
  .attr("y", function(d) {
    return yScale(d.val);
  })
  .attr("height", function(d) {
    return height - yScale(d.val);
  })
  .attr("width", barWidth);


graph
  .append("g")
  .attr('class', 'bar-label')
  .selectAll("text")
  .data(dataSet)
  .enter()
  .append("text")
  .text(d => d.val+ '%')
  .attr("y", function(d) {
    return yScale(d.val) - 5;
  }).attr('x', function(d) {
    return xScale(d.desc) + ((xScale.bandwidth() - barWidth) / 2) + (barWidth/2 - d3.select(this).node().getBBox().width/2);
  });

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
      words = text.text().split(/\s+/).reverse(),
      word,
      line = [],
      lineNumber = 0,
      lineHeight = 1,
      y = text.attr("y"),
      dy = parseFloat(text.attr("dy")),
      tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}
.bar2 {
  fill: steelblue;
}

.bar1 {
  fill: #f2f2f2;
}

text {
  font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
  <div id="graph"></div>
</div>