[英]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.