2013-05-16 24 views
0

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

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

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

我不能/不想用三个引号(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() 

回答

-1

你有三个选择:

  1. 插入手动换行符在lorem\n

  2. 使用像

    lorem = '''Lorem ipsum dolor sit amet, 
    consectetur adipisicing 
    ....''' 
    
  3. 使用正则表达式多行字符串自动替换的空间与\n后n个字符

    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)