Labeling axes with LaTeX symbols in Plot

Here’s a graph of the sine functions with the x-axis ticks labeled as multiples of \pi. I wonder if there’s an easier way to accomplish this in Observable Plot? Ideally, it would be great if tickFormat could accept a tex macro.

This is what I’d do, but it’s not a generic answer to using TeX:

Plot.plot({
  height: 180,
  marks: [
    Plot.ruleX([0]),
    Plot.ruleY([0]),
    Plot.axisY({ x: 0, ticks: 2, tickFormat: (d) => d || "" }),
    Plot.axisX({
      y: 0,
      tickFormat: (d) =>
        d === 1 ? "π" : d === -1 ? "— π" : d === 0 ? "" : `${d}π`
    }),
    Plot.line(d3.range(-4.5, 4.5, 0.001), {
      x: Plot.identity,
      y: (d) => Math.sin((Math.PI * d) / 2),
      strokeWidth: 3
    })
  ]
})

(I’m not sure about what the TeX package does, in fact — it seems that it returns both a mathml component and a svg component, together with interactions? Seems like a lot.)

Maybe it could be possible to inject those in the render transform of the axisX mark?

1 Like

Yes, I do use unicode exactly that way sometimes but I’m rather a TeX devotee and love the way it looks. Also, if you write a document in LaTeX, you can convert an SVG generated with my technique to PDF and then include that in your LaTeX file. The fonts in the resulting image will then be consistent with the ambient font in the document, which is quite a nice feature.

Yes, the TeX generated SVG is really what I’m interested in for my current use case. The interactive MathML has some really nice features, though. It’s designed to work well with assistive technologies for accessibility purposes.

I’ve sent you a suggestion, but I’m struggling to compute the bounding-box of the actual contents.

Yes, I received the suggestion and merged it - thanks! It looks pretty good as is; I suppose you want to grab the bounding box to center the tick label? I imagine the tick labels need to be rendered before the bounding box can be computed; they could then be modified.

yes that’s what I was trying to do, but the bounding box I get is much wider than the displayed contents. Also when you’ll do fractions, you’ll want to align them on the fraction line! Good luck :slight_smile:

1 Like