Matplotlib文本w /自动换行和文本突出显示

时间:2016-05-07 19:28:51

标签: python text matplotlib highlight word-wrap

我正在尝试做什么

我正在使用matplotlib,我希望能够创建一些动态脚注,能够包装和突出显示左对齐文本。

最简单的解决方案是确定一种可靠的方法,将字体大小比例转换为图形轴比例(例如,如果字体大小为8比30,则y轴上的空间占用多少文本占用空间)但我会更开心解决问题的方法。

例如:

enter image description here

我的hokey代码:

我修改了this question中的一些代码,但它仍然需要在新行上突出显示文本,因此自动换行并不完全理想。

基本上它假设段落分为三类,并相应地格式化:

  1. 纯文本
  2. 突出显示的文字
  3. 一个,非常大,字或数字
  4. 这段代码感觉非常弱,所以除了找到可以包装和突出显示文本的内容之外,我还会接受更清晰的解决方案。 **请注意,这仅适用于交互模式(例如ipython笔记本或类似),因为text.draw(fig.canvas.get_renderer())不能从非交互式工作。

    from matplotlib import transforms
    from matplotlib import pyplot as plt
    
    def parse_text_type(story, highlight_text, bold, num_tag, highlight_tag):
    
        str_list = []
        for x in story.split("___"):
            if x == 'highlight':
                str_list.append([highlight_text,highlight_tag])
            elif x == 'bold':
                str_list.append([bold,num_tag])
            elif x != '':
                str_list.append([x,"___background___"])
        return str_list
    
    def make_plot(parsed_story):
    
        ax = plt.subplot(111)
        plt.plot([0,0.5],[0,1],lw=0)
        t = plt.gca().transData
        fig = plt.gcf()
    
    
        for i,x in enumerate(parsed_story):
    
            if x[1] == '___background___':
                text = plt.text(
                -1, 1, x[0], ha='left', transform=t,
                va='top', fontsize=18, color='#999999')
    
            elif x[1] == '___highlight___':
                text = plt.text(
                    -1, 1, x[0], ha='left', transform=t, weight='bold',
                    va='top', fontsize=18, color='#32618b'
                )
    
            elif x[1] == '___bold___':
                text = plt.text(
                    -1, 1, x[0], ha='left', transform=t,
                    va='top', fontsize=100, color='#32618b', rasterized=None
                )
    
            text.draw(fig.canvas.get_renderer())
            ex = text.get_window_extent()
            t = transforms.offset_copy(text._transform, y=-ex.height - 5, units='dots')
    
            plt.axis('off');
    
        return fig, ax
    
    
    def generate_wordplot(number, highlight_text, story):
    
        num_tag = '___number___'
        highlight_tag = '___highlight___'
    
        story = story.format(number=num_tag, highlight=highlight_tag)
        parsed_story = parse_text_type(story,highlight_text, number, num_tag, highlight_tag)
    
        return make_plot(parsed_story)
    
    if __name__ == '__main__':
    
        bold = "99.9%"
        highlight_text = "humans drink water"
        story = "One survey found that {bold}of {highlight}"
    
        fig, ax = generate_wordplot(bold, highlight_text, story)
    

0 个答案:

没有答案
相关问题