2

Is it possible to use (new style) python string formatting with matplotlib's figure.text() command?

I attempt to create 2 columns of data as text (where they are meant to be aligned neatly)

import matplotlib.pyplot as plt

txt = '{0:50} {1:.4e}'.format('Row1:', 0.1542457) + '\n' + \
      '{0:50} {1:.4e}'.format('Row2:', 0.00145744) + '\n' + \
  '{0:50} {1:.4e}'.format('Long name for this row):', 0.00146655744) + '\n' + \
  '{0:50} {1}'.format('medium size name):', 'some text')

fig = plt.figure()
ax1 = fig.add_axes((0.1, 0.3, 0.8, 0.65))
ax1.plot(range(10),range(10))
fig.text(0.17, 0.07,txt)
plt.show()

which look nice when I print the txt variable to the screen:

aligned text

but is not aligned in my plot

misaligned text

1
  • 1
    I think this happens because in second case it uses non monospaced font. Commented Oct 9, 2013 at 1:11

2 Answers 2

6

You need to use a monospace font in order to keep formating:

import matplotlib.pyplot as plt

txt = '{0:50} {1:.4e}\n'.format('Row1:', 0.1542457) + \
      '{0:50} {1:.4e}\n'.format('Row2:', 0.00145744) + \
      '{0:50} {1:.4e}\n'.format('Long name for this row):', 0.00146655744) + \
      '{0:50} {1}'.format('medium size name):', 'some text')

fig = plt.figure()
ax1 = fig.add_axes((0.1, 0.3, 0.8, 0.65))
ax1.plot(range(10),range(10))
fig.text(0.17, 0.07, txt, family='monospace')
plt.show()

enter image description here

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

Comments

3

Make two strings txtL and txtR and use the multialignment kwarg but it might be hard to programatically figure out the y location for txtR.

import matplotlib.pyplot as plt

txt = '{0:50} {1:.4e}'.format('Row1:', 0.1542457) + '\n' + \
      '{0:50} {1:.4e}'.format('Row2:', 0.00145744) + '\n' + \
  '{0:50} {1:.4e}'.format('Long name for this row):', 0.00146655744) + '\n' + \
  '{0:50} {1}'.format('medium size name):', 'some text')

txtL = 'Row1:\nRow2:\nLong name for this row):\nmedium size name):'
txtR = '0.1542457\n0.00145744\n0.00146655744\nsome text'

fig = plt.figure()
ax1 = fig.add_axes((0.1, 0.3, 0.8, 0.65))
ax1.plot(range(10),range(10))
fig.text(0.17, 0.07,txtL, multialignment = 'left')
fig.text(0.7, 0.07,txtR, multialignment = 'right')

plt.show()
plt.close()

enter image description here

Comments

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.