1

我正在尝试使用 grispec 生成一组图。应该有 5 行和 2 列。前四行中的每个轴(使用 imshow)都应该显示一个图像。在左下角的轴上,我想显示/绘制一些文本。但是,文本似乎太长,无法在一行中显示。有没有办法在我称之为“文本框”的地方打印它?

我创建了一个最小的例子(见下文)。'circle.png' 可以看作是某些 png 文件的占位符。

我在 stackoverflow 上找到了两个相关示例(示例 1示例2 )。但我不确定它们如何适用于这里。

我不能/不想用三个引号(docstring)创建一个字符串变量,因为我正在从一个更大的 ascii 文件中读取文本。

另外,我不确定 gridspec 是否是最好的方法。感谢指点!

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec


def main():
    """
    goal is to show justified text in one axes of matplotlib
    """
    plt.close('all')
    fig = plt.figure(figsize=(5, 10))
    plt.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.1)

    n_rows = 5
    outer_grid = gridspec.GridSpec(n_rows, 2 )# ,wspace=0.0, hspace=0.0

    lst_files = [ 'circle.png'
                , 'circle.png'
                , 'circle.png'
                , 'circle.png'
                , 'text'
                , 'circle.png'
                , 'circle.png'
                , 'circle.png'
                , 'circle.png']

    for cur_map_id, cur_map_file in enumerate(lst_files):

        cur_row = (cur_map_id % n_rows)
        if cur_map_id / n_rows == 0:
            cur_column = 0
        else:
            cur_column = 1

        # preparation: no axes
        ax = plt.subplot(outer_grid[cur_row, cur_column], frameon=False)
        ax.axes.get_yaxis().set_visible(False)
        ax.axes.get_xaxis().set_visible(False)

        # fix for the fact that the fourth entry is text and not in tmp_lst_imgs
        if cur_map_id > 4: 
            cur_map_id = cur_map_id - 1

        # the actual plotting
        if cur_map_file == 'text':
            lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
            ax.text(0.05, 0.9, lorem, size=6)
        else:
            print cur_map_id
            im = plt.imread(cur_map_file)
            ax.imshow(im)
        ax.set_title(cur_map_file, size=6)
        fig.add_subplot(ax)

    plt.savefig('blah.png', dpi=300)
    print "done!"

if __name__ == '__main__':
    main() 
4

1 回答 1

0

你有三个选择:

  1. 手动 插入换行符\nlorem

  2. 使用多行字符串,例如

    lorem = '''Lorem ipsum dolor sit amet, 
    consectetur adipisicing
    ....'''
    
  3. 使用正则表达式自动用\nn 个字符后的 a 替换空格

    import re
    #match 80 characters, plus some more, until a space is reached
    pattern = re.compile(r'(.{80}\w*?)(\s)')  
    #keep the '80 characters, plus some more' and substitute the following space with new line
    pattern.sub(r'\1\n', lorem)
    
于 2013-05-16T14:31:59.733 回答