我有一个图表,目前看起来像
底部 Axis 应该看起来像顶部,位于最高图表尖端的正下方。我试图将底 Axis 定向到“顶部”和“底部”,但收效甚微。有任何想法吗?
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);
最佳答案
Axis 的方向仅影响标签相对于线条的位置,而不影响整体位置。如果您希望它出现在底部,您需要移动它附加到那里的元素,即
d3.select(".chart-two").append("g")
.attr("transform", "translate(0," + (height-10) + ")")
.attr("class", "axis")
.call(xBotAxis);
您可能需要根据自己的喜好调整总高度(以上 10)的偏移量和/或图表和条形的高度。
关于javascript - d3 对立图表 Axis 对齐问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20960148/