代码之家  ›  专栏  ›  技术社区  ›  agftrading

对于matplotlib子批中的标题,有没有方法将纯色背景扩展到页面的全宽?

  •  0
  • agftrading  · 技术社区  · 6 年前

    我有一个包含多个matplotlib子批的页面。我最初通过部署以下代码为这些子批次添加了标题:

    title = fig.suptitle('This is a title',horizontalalignment='center',verticalalignment='top')
    

    因此,我使用以下代码设置标题:

    fig.text(x=0.5,y=0.97,ha='center',va='top',s='This is a title',color='w',backgroundcolor='blue')
    

    这确实添加了背景色,但它只延伸到文本本身之外,如所附图像所示。

    enter image description here

    有没有一种方法可以直接写在图形画布上,即用图suptitle或者图文本方法。对其他实现目标的解决方案持开放态度,但我希望避免将子批次ax对象本身作为标题部署(这似乎有点粗糙)。

    谢谢!

    *更新*

    我已尝试部署以下代码:

    title = fig.text(x=0.5,y=0.97,ha='center',va='top',s='This is a title',color='w',backgroundcolor='blue')
    
    bb = title.get_bbox_patch()
    
    bb.set_width(w=100)
    

    *更新*

    进一步看另一篇文章,给出了一个潜在的解决方案,这确实有效!

    title = fig.text(x=0.5,y=0.97,ha='center',va='top',s='This is a title',color='w',backgroundcolor='blue')
    
    title._bbox_patch._mutation_aspect = 0.02
    
    title.get_bbox_patch().set_boxstyle("square", pad=47.8)
    

    请参阅下面的更新图片:

    enter image description here

    必须有一个更规定的蟒蛇方法来影响这个结果,但更具体的控制位置和背景颜色的大小!这就是我真正在寻找的解决方案!

    谢谢!

    1 回复  |  直到 6 年前
        1
  •  1
  •   ImportanceOfBeingErnest    6 年前

    您可以直接应用中提供的解决方案 How do I make the width of the title box span the entire plot? 只需稍作修改,就可以使用图形宽度而不是子图宽度作为子图的水平大小。

    import matplotlib.pyplot as plt
    
    from matplotlib.path import Path
    from matplotlib.patches import BoxStyle
    
    
    class ExtendedTextBox(BoxStyle._Base):
        """
        An Extended Text Box that expands to the axes limits 
                            if set in the middle of the axes
        """
    
        def __init__(self, pad=0.3, width=500.):
            """
            width: 
                width of the textbox. 
                Use `ax.get_window_extent().width` 
                       to get the width of the axes.
            pad: 
                amount of padding (in vertical direction only)
            """
            self.width=width
            self.pad = pad
            super(ExtendedTextBox, self).__init__()
    
        def transmute(self, x0, y0, width, height, mutation_size):
            """
            x0 and y0 are the lower left corner of original text box
            They are set automatically by matplotlib
            """
            # padding
            pad = mutation_size * self.pad
    
            # we add the padding only to the box height
            height = height + 2.*pad
            # boundary of the padded box
            y0 = y0 - pad
            y1 = y0 + height
            _x0 = x0
            x0 = _x0 +width /2. - self.width/2.
            x1 = _x0 +width /2. + self.width/2.
    
            cp = [(x0, y0),
                  (x1, y0), (x1, y1), (x0, y1),
                  (x0, y0)]
    
            com = [Path.MOVETO,
                   Path.LINETO, Path.LINETO, Path.LINETO,
                   Path.CLOSEPOLY]
    
            path = Path(cp, com)
    
            return path
    
    
    # register the custom style
    BoxStyle._style_list["ext"] = ExtendedTextBox
    
    fig, ax = plt.subplots()
    # set the title position to the horizontal center (0.5) of the axes
    title = fig.suptitle('My Log Normal Example', position=(.5, 0.96), 
                         backgroundcolor='black', color='white')
    # set the box style of the title text box to our custom box
    bb = title.get_bbox_patch()
    
    
    def resize(event):
        # use the figure width as width of the text box 
        bb.set_boxstyle("ext", pad=0.4, width=fig.get_size_inches()[0]*fig.dpi )
    
    resize(None)
    # Optionally: use eventhandler to resize the title box, in case the window is resized
    cid = plt.gcf().canvas.mpl_connect('resize_event', resize)
    
    # use the same dpi for saving to file as for plotting on screen
    plt.savefig(__file__+".png", dpi="figure")
    plt.show()
    

    enter image description here