d3反对图表轴对齐问题

时间:2014-01-06 22:03:39

标签: javascript charts d3.js axis

我的图表目前看起来像enter image description here

底部轴应该看起来像顶部,位于最高图表尖端的正下方。我试图将底轴设置为“顶部”和“底部”,但效果不大。有任何想法吗?

var width = 960,
fullHeight = 850,
height = 350;

var y = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([height, 0]);

var axisScale = d3.scale.ordinal()
    .domain(data)
    .rangeBands([0, width]);

var axisScale2 = d3.scale.ordinal()
    .domain(data2)
    .rangeBands([0, width]);
    // .range([0, 960]);

var chart = d3.select(".chart")
    .attr("width", width)
    .attr("height", fullHeight);

var chart1 = chart.append("g")
    .attr("class", "chart-one")
    .attr("height", height)
    .attr("width", width);


var chart2 = chart.append("g")
    .attr("class", "chart-two")
    .attr("transform", function() { return "translate(0," + (height + 70) + ")"; })
    .attr("height", height)
    .attr("width", width);

var barWidth = width / data.length;

var bar = d3.select(".chart-one")
    .selectAll("g")
    .data(data)
    .enter().append("g")
    .attr("class", "one")
    .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });

bar.append("rect")
    .attr("y", function(d) { console.log(d, y(d)); return y(d) + 60; })
    .attr("height", function(d) { return height - y(d); })
    .attr("width", barWidth - 1);


var bar2 = d3.select(".chart-two")
    .selectAll("g")
    .data(data2)
    .enter().append("g")
    .attr("class", "two")
    .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });

bar2.append("rect")
    .attr("height", function(d) { return height - y(d) })
    .attr("width", barWidth - 1);

var xAxis = d3.svg.axis()
    .scale(axisScale)
    .tickValues(data);
    // .tickPadding([-10]);
    // .orient("top");
var xAxis2 = d3.svg.axis()
    .scale(axisScale2)
    .tickValues(data2)
    .tickPadding([15]);

var xAxis3 = d3.svg.axis()
    .scale(axisScale)
    .tickValues(data)
    .tickPadding(27);

var xBotAxis = d3.svg.axis()
    .scale(axisScale)
    .orient("top")
    .tickValues(data);

d3.select(".chart-one").append("g").attr("class", "axis").call(xAxis);
d3.select(".chart-one").append("g").attr("class", "axis").call(xAxis2);
d3.select(".chart-one").append("g").attr("class", "axis").call(xAxis3);

d3.select(".chart-two").append("g").attr("class", "axis").call(xBotAxis);

1 个答案:

答案 0 :(得分:1)

轴的方向仅影响标签相对于线的位置,而不影响整体位置。如果你想让它出现在底部,你需要将它附加的元素移动到那里,即

d3.select(".chart-two").append("g")
  .attr("transform", "translate(0," + (height-10) + ")")
  .attr("class", "axis")
  .call(xBotAxis);

您可能想根据自己的喜好调整总高度(上方10)和/或图表和条形高度的偏移量。