I am trying to get a little percent sign superscript.
I found and example which works but not percent
var svgText = svg.append(\'text\').text(\'This
Why not use a tspan
? This will allow you to format any text how you want, superscript or otherwise, no matter if there is a unicode superscript symbol you can use:
Within a element, text and font properties and the current text position can be adjusted with absolute or relative coordinate values by including a
element. (MDN)
There are a few approaches you could take in this regard, but if you can extract the text that needs to be superscript (or generate it on the fly), then you can create the superscript and regular text relatively easly. Below I use a tspan
to hold the regular text and another to hold the superscript:
var svg = d3.select("body").append("svg");
var data = [
{text: "Here's some normal text", super:"Here's superscript"},
{text:"Some text", super:"α,β,γ,%,!,1,2,3"}
];
var text = svg.selectAll()
.data(data)
.enter()
.append("text")
.attr("x", 10)
.attr("y", function(d,i) { return i * 20 + 20; });
// Main content:
text.append("tspan")
.text(function(d) { return d.text; })
.attr("font-size", 14)
// Superscript content:
text.append("tspan")
.text(function(d) { return " " +d.super; })
.attr("dy",-5)
.attr("font-size",11)
With a bit of string manipulation you could use this pattern without pre-existing properties for each text string (below I use only one text span with normal text just being added as normal):
var svg = d3.select("body").append("svg");
var data = [
"Length is 10px - 10%",
"Height is 20px - 30%"
];
var text = svg.selectAll()
.data(data)
.enter()
.append("text")
.attr("x", 10)
.attr("y", function(d,i) { return i * 20 + 20; })
.text(function(d) {
return d.split("-")[0];
});
// Superscript content:
text.append("tspan")
.text(function(d) { return d.split("-")[1]; })
.attr("dy",-5)
.attr("font-size",11)
The tspan
approach is useful in that it maintains text position, which is easier to manage than placing multiple text
elements where the position of each depends on the width of other text
elements.