我正在使用 Angular 7 和 D3JS V4 来实现条形图,我需要在条形顶部显示 y 轴标签值,我尝试了多种方案但未能做到,请帮我做所以..提前谢谢。
//Initialize SVG
this.svg = d3.select("#bar-chart");
this.width = +this.svg.attr("width") - this.margin.left - this.margin.right;
this.height =
+this.svg.attr("height") - this.margin.top - this.margin.bottom;
this.g = this.svg
.append("g")
.attr(
"transform",
"translate(" + this.margin.left + "," + this.margin.top + ")"
);
//Initialize Axis
this.x = d3Scale
.scaleBand()
.rangeRound([0, this.width])
.padding(0.9);
this.y = d3Scale.scaleLinear().rangeRound([this.height, 0]);
this.x.domain(this.totalStores.map(d => d.store));
this.y.domain([0, d3Array.max(this.totalStores.map(d => d.storeCount))]);
//Draw Axis
this.g
.append("g")
.attr("transform", "translate(0," + this.height + ")")
.call(d3Axis.axisBottom(this.x));
this.g
.append("g")
.call(d3Axis.axisLeft(this.y).ticks(4))
.append("text");
//Draw Bars
this.g
.selectAll(".bar")
.data(this.totalStores)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", d => this.x(d.store))
.attr("y", d => this.y(d.storeCount))
.attr("width", this.x.bandwidth())
.attr("height", d => this.height - this.y(d.storeCount));
最佳答案
只需将 x 和 y 值传递给文本即可
// Get the y axis value on top
this.g
.selectAll("text.bar")
.data(this.totalStores)
.enter()
.append("text")
.attr("class", "yAxis-label")
.attr("text-anchor", "middle")
.attr("fill", "#70747a")
.attr("x", d => this.x(d.store))
.attr("y", d => this.y(d.storeCount) - 5)
.text(d => d.storeCount);
关于javascript - D3 JS条形图,在条形顶部显示y轴标签值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56521904/