我正在使用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));
答案 0 :(得分:1)
只需将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);
答案 1 :(得分:0)
我这样画我的y轴:
drawYAxis(g: d3.Selection<SVGElement, {}, null, undefined> = this.yAxis) {
g.selectAll(".label").remove();
return g.call(
d3.axisLeft(this.y)
.ticks(getTickFrequency(this.axes[1].format, this.y.domain()))
.tickSizeInner(this.x.range()[0] - this.x.range()[1])
.tickSizeOuter(0)
.tickFormat(Formatter.short(this.axes[1].format)))
.call(g => g.select(".tick:last-of-type text")
.clone()
.classed("label", true)
.attr("x", 5 - this.margin.left)
.text(this.axes[1].label));
}
因此,我像您一样绘制y轴,使用d3.axisLeft
和一些其他选项,然后选择附加到类text
的最后一个<g>
的{{1}} ,然后复制元素及其样式等。然后将其向左移动一点,给它一个不同的类,然后将文本设置为预定义的标签。
类似的事情应该起作用。请记住,您可以添加不同的类并更改位置以更好地满足您的需求
tick