Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add superscript & subscript in text in D3

Tags:

d3.js

Current Code:

.text(function(){return "Area:"+d3.values(expensesTot)[count].area+"mm2";
 });

Current Output:

Area: 20mm2

Expected Output:

Area: 20mm2

like image 555
Ani Menon Avatar asked Jun 09 '16 08:06

Ani Menon


2 Answers

From this example : http://bl.ocks.org/mbostock/6738109

You can just do the following :

.text(function(){return "Area:"+d3.values(expensesTot)[count].area+"mm²";
 });

Working example :

var svg = d3.select('body').attr('width', 500).attr('height', 500);

var svgText = svg.append('text').text('This is a test : mm²')
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
like image 124
thatOneGuy Avatar answered Oct 11 '22 00:10

thatOneGuy


The accepted answer works only for numbers, so for anyone wanting to sub/sup-script their text, here's two methods:

  1. Use SVG's tspan element:

Example (note that it is appended after a text element):

svg.append('text')
  .attr('x', width / 2)
  .attr('y', height / 2)
  .html('Normal Text')
  .style('font-size', '2rem')
  .append('tspan')
    .text('Subscrit Text')
    .style('font-size', '.1rem')
    .attr('dx', '.1em')
    .attr('dy', '.9em')
  1. Use SVG's foreignObject element (note, this method requires styling via css, and (from my experimentation) requires inline styling:

Example with inline css:

svg.append("foreignObject")
  .attr("x", width / 2)
  .attr("y", height / 2)
  .append("xhtml:body")
  .html("<p style='font-family:consolas;'=>mm<sup>2</sub></p>")

As far as I can tell, the tspan method is 'correct' solution, as it allows for styling via SVG attributes, but either will work for using sub/super-scripts with D3.

like image 26
Jared Wilber Avatar answered Oct 11 '22 02:10

Jared Wilber