对齐 matplotlib.pyplot.figtext 中的列

Aligning Columns in matplotlib.pyplot.figtext

(towns_n和Towns是两个数组,每个数组分别有50个数字和名字)

count = 0 
for number,town in zip(towns_n,Towns):
    textString += (number +'.'+ town).ljust(35)
    count += 1
    if count == 6:
        count = 0
        textString += '\n' 
plt.figtext(0.13,0.078,textString)

我的问题是我想绘制 6 列。

如果我 print 我的字符串看起来完全符合预期,它看起来像 6 列对齐。但是如果我沿着我的其他图像绘制它,它看起来根本不对齐。
我认为这不重要,但我的其他图像是地图使用底图。我正在我的地图下方绘制此字符串。

What I am getting

编辑:您可以尝试生成 50 个随机字符串和数字,这样您就不需要实际的城镇列表。

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

Towns=[]
towns_n=[]

for i in range(50):
    string = id_generator()
    Towns.append(string);
    towns_n.append(str(i))

如评论中所述,一种解决方案是使用 monospaced font

plt.figtext(..., fontname="DejaVu Sans Mono")

示例:

import random
import string
import matplotlib.pyplot as plt

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

Towns=[]
towns_n=[]

for i in range(50):
    string = id_generator()
    Towns.append(string);
    towns_n.append(str(i))


count = 0 
textString =""
for number,town in zip(towns_n,Towns):
    textString += (number +'.'+ town).ljust(12)
    count += 1
    if count == 6:
        count = 0
        textString += '\n'

fig = plt.figure()
fig.add_subplot(111)
fig.subplots_adjust(bottom=0.5)
plt.figtext(0.05,0.078,textString, fontname="DejaVu Sans Mono")

plt.show()

另一个选项是分别创建每一列:

import random
import string
import matplotlib.pyplot as plt

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

Towns=[]
towns_n=[]

for i in range(50):
    string = id_generator()
    Towns.append(string);
    towns_n.append(str(i))


fig = plt.figure()
fig.add_subplot(111)
fig.subplots_adjust(bottom=0.5)

space = 0.05
left = 0.05
width= 0.15
for i in range(6):
    t = [towns_n[i::6][j] + ". " + Towns[i::6][j] for j in range(len(towns_n[i::6]))]
    t = "\n".join(t)
    plt.figtext(left+i*width,0.35,t, va="top", ha="left")

plt.show()