从D3中的字符串数组创建轴?

时间:2017-05-26 04:43:26

标签: javascript d3.js

我已经从整数数组中创建了d3中的基本条形图。

  let maxWidth = $('body').width();

  let chartWidth = maxWidth * 0.75; // also arbitrary
  let chartHeight = chartWidth / _GoldenRatio;

  let barWidth = (chartWidth / dataArray.length) - horizontalSpacing;

  let barHeightUnit = chartHeight / d3.max(dataArray);

  let mainChart = d3.select(containerSelector)
    .append('svg')
    .attr('width', chartWidth)
    .attr('height', chartHeight);

  mainChart.selectAll("rect")
    .data(dataArray)
    .enter()
    .append("rect")
    .attr("class", "bar")
    .attr("height", function(d, i) { return (d * barHeightUnit) })
    .attr("width",barWidth)
    .attr("x", function(d, i) { return i * (barWidth + horizontalSpacing) + horizontalSpacing })
    .attr("y", function(d, i) { return chartHeight - (d * barHeightUnit) });

我用几个不同的数组做了几次。每个整数列表对应于我希望沿x轴显示的字符串列表。每个字符串都位于一个条形下方以标记它。

我无法通过d3或d3轴找到一种方法。从这个字符串列表构造轴的简单方法是什么?

1 个答案:

答案 0 :(得分:1)

希望使用d3.v4的这个片段有帮助。



var margin = {
    top: 100,
    right: 100,
    bottom: 100,
    left: 100
  },
  width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var x = d3.scaleBand()
  .range([0, width])
  .domain(["apple", "orange", "banana", "grapefruit"]);

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

<script src="https://d3js.org/d3.v4.min.js"></script>
&#13;
&#13;
&#13;