1

I want to put two lines of text with some numbers on a plot. It works perfectly (Example 1).

However, I need some of the text to be superscript. When I use $^{text}$ my \n newline character seems to get bigger, which breaks my alignment in the plot as in Example 2. The difference isn't much, but it is enough to be causing me problems.

Is there any way I can keep the original spacing of the newline character and also include superscript formatting? I know there are a few posts on similar topics, but mainly cover the use of raw strings rather than the size of the newline itself.

A simple and complete example:

import matplotlib.pyplot as plt
n=100

#Example 1
plt.text(0,0.01,'Hello: '+str(n)+'\n'+'TEST')
#Example 2
plt.text(0.2,0.01,'Hello: '+str(n)+'\n'+r'TEST1$^{problem}$')
1
  • A workaround would be to not use a newline character but break each text object into two text objects, one for each line. Then you can obviously set the alignment explicitly. Commented Apr 10, 2019 at 9:46

1 Answer 1

2

You can set the linespacing of the text manually.

import matplotlib.pyplot as plt
n=100
#plt.axhline(0.06, alpha=0.4)
text_kw = dict(verticalalignment="baseline", fontsize=10)
#Example 1
plt.text(0,0.01,'Hello: '+str(n)+'\n'+'TEST', linespacing=1.5, **text_kw)
#Example 2
plt.text(0.2,0.01,'Hello: '+str(n)+'\n'+r'TEST1$^{problem}$', linespacing=1.2, **text_kw)
plt.show()

enter image description here

In this case, values for of 1.2 for the text with mathtext and 1.5 for the text without mathtext seem to give good results.

In general however you will need to adapt those values to the actual text and also the fontsize in use.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Perfect solution, thanks. I should have checked for the linespacing keyword. This does feel like a funny use case but it is interesting that mathtext changes formatting like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.