[英]D3 JS bar chart, show y-axis label value at the top of the bar
我正在使用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);
我这样画我的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
和一些其他选项,然后选择带有类tick
的最后一个<g>
附加的text
,并复制元素的样式, d3.axisLeft
。然后移动它左边一点,给它一个不同的类,然后将文本设置为预定义的标签。
这样的事情应该起作用。 请记住,您可以添加不同的类并更改定位以更好地满足您的需求
this.g
.append("g")
.call(d3Axis.axisLeft(this.y).ticks(4))
.select(".tick:last-of-type")
.append("text")
.text("My axis label");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.