我有一个显示正值和负值的条形图。有没有办法让 x 轴与零值同步?此外,x 轴上的刻度似乎不限于指定的 5。有没有办法解决这些问题?
var xAxis = d3.axisBottom()
.scale(x)
.tickFormat(d3.timeFormat("%b %Y"))
.ticks(5);
这是包含代码的 fiddle
https://jsfiddle.net/umshqLyj/3/
最佳答案
使用您的 y
比例来平移轴:
g.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + y(0) + ")")
.call(xAxis);
这是带有该更改的代码:
var margin = {
top: 20,
right: 20,
bottom: 70,
left: 40
},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.isoParse;
var x = d3.scaleBand().rangeRound([0, width], .05).padding(0.1);
var y = d3.scaleLinear().range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x)
.tickFormat(d3.timeFormat("%b %Y"))
.ticks(5);
var yAxis = d3.axisLeft()
.scale(y)
.ticks(5);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
var g = svg.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var data = [{
date: '2016-03-02T00:00:00-05:00',
value: 5
}, {
date: '2016-04-03T00:00:00-05:00',
value: 1
}, {
date: '2016-05-04T00:00:00-05:00',
value: -2
}, {
date: '2016-06-05T00:00:00-05:00',
value: 3
}, {
date: '2016-07-06T00:00:00-05:00',
value: 3
}, {
date: '2016-08-07T00:00:00-05:00',
value: 4
}, {
date: '2016-09-08T00:00:00-05:00',
value: 4
}, {
date: '2016-11-09T00:00:00-05:00',
value: 4
}, {
date: '2016-12-10T00:00:00-05:00',
value: -3
}, {
date: '2017-01-11T00:00:00-05:00',
value: 5
}, {
date: '2017-02-12T00:00:00-05:00',
value: 3
}, {
date: '2017-03-13T00:00:00-05:00',
value: -4
}, {
date: '2017-04-14T00:00:00-05:00',
value: 2
}, {
date: '2017-05-15T00:00:00-05:00',
value: 4
}];
data.forEach(function(d) {
d.date = parseDate(d.date);
d.value = +d.value;
});
x.domain(data.map(function(d) {
return d.date;
}));
y.domain([-5, 5]);
g.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Value");
g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function(d) {
if (d.value > 0) {
return 'bar blue';
} else {
return 'bar red';
}
})
.attr("x", function(d) {
return x(d.date);
})
.attr("width", x.bandwidth())
.attr("y", function(d) {
return y(Math.max(0, d.value));
})
.attr("height", function(d) {
return Math.abs(y(d.value) - y(0));
});
g.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + y(0) + ")")
.call(xAxis);
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.blue:hover {
fill: steelblue;
}
.red:hover {
fill: brown;
}
.red {
fill: red;
}
.blue {
fill: blue;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
关于javascript - 将 x 轴与零刻度 d3 条形图对齐,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46674301/