如何在matplotlib图文中使用(新样式)字符串格式

时间:2013-10-09 00:45:53

标签: python string text matplotlib format

是否可以使用matplotlib的figure.text()命令使用(新样式)python字符串格式?

我尝试创建2列数据作为文本(它们意味着整齐排列)

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()

当我将txt变量打印到屏幕时看起来不错:

aligned text

但未在我的情节中对齐

misaligned text

2 个答案:

答案 0 :(得分:5)

您需要使用等宽字体才能保持格式化:

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

答案 1 :(得分:3)

创建两个字符串txtL和txtR并使用multialignment kwarg,但可能很难以编程方式找出txtR的y位置。

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