【问题标题】:How do I format tabular text in matplotlib plots?如何在 matplotlib 图中格式化表格文本?
【发布时间】:2022-02-13 18:25:42
【问题描述】:

在我的代码中,我有类似的东西:

    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot()

    ...
    
    fmtstr = '{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}'
    ntext = fmtstr.format('    ', 'tot', 'unique',
            'in  ', str(len(seqzs[fp])), str(len(seqzsSet[fp])),
            'std ', str(len(seqzs[std])), str(len(seqzsSet[std])),
            'shrd', '', str(len(dRTShrd)))

    ax.text(0.03, 0.8, ntext, transform=ax.transAxes)
    print(ntext)
    ...

    plt.savefig(os.path.join(outDir, oname))

printed 时,格式化文本ntext 看起来不错:

               tot            unique         
in             6826           3837           
std            24773          11376          
shrd                          3220           

但剧情不好:

如何在情节中正确使用它? (数字的宽度随着每个图的变化而变化,所以我需要一个常量格式化程序)

【问题讨论】:

标签: python matplotlib


【解决方案1】:

像这样使用等宽字体:(感谢@Aziz 的建议。)

    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot()

    ...
    
    fmtstr = '{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}'  # format string
    ntext = fmtstr.format('    ', 'tot', 'unique',
            'in  ', str(len(seqzs[fp])), str(len(seqzsSet[fp])),
            'std ', str(len(seqzs[std])), str(len(seqzsSet[std])),
            'shrd', '', str(len(dRTShrd)))
    ax.text(0.03, 0.8, ntext, transform=ax.transAxes, fontname = 'monospace')

    ...

    plt.savefig(os.path.join(outDir, oname))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2015-10-26
    • 2013-04-13
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多