Matplotlib文本对齐 [英] Matplotlib text alignment
本文介绍了Matplotlib文本对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法只用一个 ax.text()
命令就可以得到第三个轴中显示的结果?使用 expandtabs
几乎可以让我到达那里,但文本永远不会正确对齐.
Is there a way to get the result shown in the third axes with just a single ax.text()
command? Using expandtabs
almost get me there, but the text never aligns properly.
在我看来,使用两个绘图命令似乎不是一种好习惯,并且您始终需要猜测两者之间的距离,这可能需要一些迭代.
Using two plotting commands doesn't seem like a good practice to me, and you always need to guess the distance between both, which might take some iterations.
fig, axs = plt.subplots(1,3, figsize=(12,4),
subplot_kw={'aspect': 1, 'xticks': [], 'yticks':[]})
fig.subplots_adjust(wspace=0.05)
values = {'a': 1.35, 'b': 25.1, 'c': 5}
tmpl = """Param1: {a:1.1f}
Long param2: {b:1.1f}
Prm3: {c:1.1f}"""
mystr = tmpl.format(**values)
axs[0].text(0.1, 0.9, mystr, va='top', transform=axs[0].transAxes)
axs[0].set_title('Default')
tmpl = """Param1:\t\t\t{a:1.1f}
Long param2:\t{b:1.1f}
Prm3:\t\t\t{c:1.1f}""".expandtabs()
mystr = tmpl.format(**values)
axs[1].text(0.1, 0.9, mystr, va='top', transform=axs[1].transAxes)
axs[1].set_title('Almost there')
labels = """Param1:
Long param2:
Prm3:"""
tmpl = """{a:1.1f}
{b:1.1f}
{c:1.1f}"""
mystr = tmpl.format(**values)
axs[2].text(0.1, 0.9, labels, va='top', transform=axs[2].transAxes)
axs[2].text(0.65, 0.9, mystr, va='top', ha='right', transform=axs[2].transAxes)
axs[2].set_title('Target')
推荐答案
使用等宽字体,以便每个字符占用相同的空间.
Use a monospaced font so that each character takes the same amount of space.
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1,3, figsize=(12,4),
subplot_kw={'aspect': 1, 'xticks': [], 'yticks':[]})
fig.subplots_adjust(wspace=0.05)
values = {'a': 1.35, 'b': 25.1, 'c': 5}
tmpl = """Param1: {a:1.1f}
Long param2: {b:1.1f}
Prm3: {c:1.1f}"""
mystr = tmpl.format(**values)
axs[0].text(0.1, 0.9, mystr, va='top', transform=axs[0].transAxes)
axs[0].set_title('Default')
mono = {'family' : 'monospace'}
textblock = "1234567890\nabcdefghij\nABCDEFGHIJ\n 0"
axs[1].text(0.1, 0.9, textblock, va='top', transform=axs[1].transAxes, fontdict=mono)
axs[1].set_title('Monospaced text block')
axs[2].text(0.1, 0.9, textblock, va='top', transform=axs[2].transAxes)
axs[2].set_title('Not monospaced')
plt.show()
这篇关于Matplotlib文本对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文