在matplotlib.pyplot.figtext中对齐列

时间:2017-11-02 23:30:29

标签: python matplotlib alignment python-3.6

(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列。

如果我打印我的字符串看起来完全符合预期,它看起来像6个对齐的列。但如果我沿着我的其他图像绘制它,它看起来根本不对齐 我不认为这很重要,但我的另一张图片是地图usign底图。我正在我的地图下方绘制这个字符串。

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

1 个答案:

答案 0 :(得分:1)

如评论中所述,一种解决方案是使用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()

enter image description here

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

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

enter image description here