【问题标题】:Aligning Columns in matplotlib.pyplot.figtext在 matplotlib.pyplot.figtext 中对齐列
【发布时间】:2018-04-15 14:54:13
【问题描述】:

(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 个对齐的列。但是,如果我沿着我的其他图像绘制它,它看起来根本没有对齐。
我认为这并不重要,但我的其他图像是地图使用底图。我正在我的地图下方绘制这个字符串。

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

【问题讨论】:

  • 您能否提供一张您在这里谈论的内容的图片?另外,请提供问题的minimal reproducible example
  • 我猜你想要做的事情需要monospaced font。你考虑过使用一个吗?否则,您将需要创建 6 个单个文本元素(每个“列”一个)。同样,提供minimal reproducible example 以获得答案(或者您是否希望有人输入英国所有城市?)。
  • 谢谢,我想我要放弃了,按照你对 6 个字符串的建议去做。我在上次编辑中添加了一些内容,以便您可以获得 50 个随机单词和数字。

标签: python matplotlib alignment python-3.6


【解决方案1】:

正如 cmets 中所说,一种解决方案是使用 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()

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 2021-12-15
    • 1970-01-01
    • 2022-11-08
    • 2011-11-09
    • 2017-01-11
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多