我已經使用 svg 創建了離散圖例,我想將索引顯示為其標簽。
// creating svg
selectedLegend
.append("svg")
.attr("viewBox", `0 0 ${count} 1`)
.attr("preserveAspectRatio", "none")
function legend(g: any) {
// appending data
g.selectAll("g.legendCells")
.data(itemColor)
.enter()
.append("rect");
// appending text for label, which is not working as expected
g.selectAll("rect")
.append("text")
.attr("class", "breakLabels")
.style("fill", "red")
.attr("x", cellWidth cellPadding)
.attr("y", 5 cellHeight / 2)
.text(function (d: Record<string, unknown>, i: any) {
// return the index, which should be label for legend
return i;
});
}
小提琴鏈接:
uj5u.com熱心網友回復:
注意不要將<text>元素作為子元素放置到<rect>. 他們是獨立的。縮放 ( preserveAspectRatio="none") 也適用于文本,因此在另一個 SVG 中包含一個 SVG 可能是個好主意。內部 SVG 具有縮放比例,外部 SVG 具有文本。外部 SVG 有一個與高/寬比匹配的 viewBox(10 比 1 = 250 比 25)。
在上面<text>我添加了屬性 dominant-baseline="middle"并將text-anchor="middle"文本的句柄定位在它的中間。
<div id="container">
<svg viewBox="0 0 20 2" width="400px">
<svg viewBox="0 0 4 1" preserveAspectRatio="none" width="100%" height="1" >
<rect x="0" y="0" height="1" width="1" style="fill: rgb(255, 46, 0);"/>
<rect x="1" y="0" height="1" width="1" style="fill: rgb(0, 184, 0);"/>
<rect x="2" y="0" height="1" width="1" style="fill: rgb(0, 25, 255);"/>
<rect x="3" y="0" height="1" width="1" style="fill: rgb(179, 179, 179);"/>
</svg>
<g dominant-baseline="middle" text-anchor="middle" font-size=".73">
<text x="2.5" y="1.5" style="fill: black;">0</text>
<text x="7.5" y="1.5" style="fill: black;">1</text>
<text x="12.5" y="1.5" style="fill: black;">2</text>
<text x="17.5" y="1.5" style="fill: black;">3</text>
</g>
</svg>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/451849.html
上一篇:修改后的模板文字型別
