【问题标题】:How do I make the width of the title box span the entire plot?如何使标题框的宽度跨越整个情节?
【发布时间】:2017-04-09 07:56:45
【问题描述】:

考虑以下熊猫系列s 和情节

import pandas as pd
import numpy as np

s = pd.Series(np.random.lognormal(.001, .01, 100))
ax = s.cumprod().plot()
ax.set_title('My Log Normal Example', position=(.5, 1.02),
             backgroundcolor='black', color='white')

如何让包含标题的框跨越整个情节?

【问题讨论】:

  • 我唯一能想到的就是手动设置。假设您的figsize=(9,7),然后是您的标题大小,手动设置:size=40.5。但是,我也很想知道是否有其他方法。

标签: python pandas matplotlib


【解决方案1】:

当然可以得到标题的边界框,它是一个Text 元素。这可以通过

title = ax.set_title(...) 
bb = title.get_bbox_patch() 

原则上,然后可以操纵边界框,例如通过 bb.set_width(...)。但是,一旦 matplotlib 将标题绘制到画布上,所有设置都会丢失。至少我是这样解释Textdraw()方法的。

我不知道设置边界框的其他方法。例如,legend 的边界框可以通过
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, mode="expand") 设置,使其扩展到整个轴范围(请参阅here)。对Text 也有相同的选项会非常有用。但就目前而言,我们没有。

Text 对象允许设置bbox 参数,该参数通常用于设置边界框的样式。无法设置边界框范围,但它接受一些周围框属性的字典。并且接受的属性之一是boxstyle。默认情况下,这是一个square,但可以设置为圆形或箭头或其他奇怪的形状。

那些boxstyles 实际上是可能的解决方案的关键。它们都继承自 BoxStyle._Base 并且 - 正如在 the bottom of the annotations guide 中所见 - 可以定义自定义形状,子类化 BoxStyle._Base

以下解决方案基于 BoxStyle._Base 的子类化,它接受轴的宽度作为参数,并绘制标题的矩形路径,使其恰好具有该宽度。

作为奖励,我们可以注册一个事件处理程序,以便该宽度一旦由于调整窗口大小而发生变化,就会得到调整。

代码如下:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

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

dpi = 80

# register the custom style
BoxStyle._style_list["ext"] = ExtendedTextBox

plt.figure(dpi=dpi)
s = pd.Series(np.random.lognormal(.001, .01, 100))
ax = s.cumprod().plot()
# set the title position to the horizontal center (0.5) of the axes
title = ax.set_title('My Log Normal Example', position=(.5, 1.02), 
             backgroundcolor='black', color='white')
# set the box style of the title text box toour custom box
bb = title.get_bbox_patch()
# use the axes' width as width of the text box
bb.set_boxstyle("ext", pad=0.4, width=ax.get_window_extent().width )


# Optionally: use eventhandler to resize the title box, in case the window is resized
def on_resize(event):
    print "resize"
    bb.set_boxstyle("ext", pad=0.4, width=ax.get_window_extent().width )

cid = plt.gcf().canvas.mpl_connect('resize_event', on_resize)

# use the same dpi for saving to file as for plotting on screen
plt.savefig(__file__+".png", dpi=dpi)
plt.show()


如果有人对更轻的解决方案感兴趣,还可以选择使用标题边界框的mutation_aspect,在绘制标题时显然保持不变。虽然mutation_aspect 本身基本上只改变了盒子的高度,但可以为盒子使用极大的填充并将mutation_aspect 设置为一个非常小的数字,这样最后盒子的宽度就会显示出来。这种解决方案的明显缺点是,填充和方面的值必须通过反复试验才能找到,并且会随着不同的字体和图形大小而改变。 在我的例子中,mutation_aspect = 0.04pad=11.9 的值会产生所需的结果,但在其他系统上,它们当然可能会有所不同。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

s = pd.Series(np.random.lognormal(.001, .01, 100))
ax = s.cumprod().plot()
title = ax.set_title('My Log Normal Example', position=(.5, 1.02),
             backgroundcolor='black', color='white',
             verticalalignment="bottom", horizontalalignment="center")
title._bbox_patch._mutation_aspect = 0.04
title.get_bbox_patch().set_boxstyle("square", pad=11.9)
plt.tight_layout()
plt.savefig(__file__+".png")
plt.show()

【讨论】:

  • 我不知道赏金今天结束了,好的解决方案需要一段时间才能输入。;-)
  • 这是一个绝妙的答案。
  • 我开始了新的赏金任务。几乎可以肯定,它会在 24 小时内归您所有。除非其他人提出更好的答案(我对此表示怀疑,但可能)。
【解决方案2】:

您可以在主轴上方创建一个辅助轴,并将其用作标题的“框”,而不是缩放标题文本本身的边界框。由于轴通常看起来不像框,我们将关闭其轴标签和刻度,并将背景颜色设置为黑色以匹配 OP。

我正在使用与 here 相同的方法来制作辅助的匹配轴。

此外,我使用AnchoredText 将标题文本捕捉到轴上,以便它可以轻松地定位在它的中心。

import matplotlib.pyplot as plt 
from matplotlib.offsetbox import AnchoredText
from mpl_toolkits.axes_grid1 import make_axes_locatable
import pandas as pd
import numpy as np

s = pd.Series(np.random.lognormal(.001, .01, 100))
ax = s.cumprod().plot()

divider = make_axes_locatable(ax)
cax = divider.append_axes("top", size="11%", pad=0)
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.set_facecolor('black')

at = AnchoredText("My Log Normal Example", loc=10,
                  prop=dict(backgroundcolor='black',
                            size=12, color='white'))
cax.add_artist(at)

plt.show()

编辑:对于较旧的matplotlib 版本,您在设置背景颜色时可能需要切换到cax.set_axis_bgcolor('black')

【讨论】:

  • 你说,“而不是缩放标题文本本身的边界框......”。您知道通过设置Text 的边界框来实际解决此问题的方法吗?这个选项是否存在?
  • 我想人们不得不修补边界框的填充。问题是它在所有方向上均按标量值进行缩放。可能有一种方法可以仅在水平方向设置大填充(this 看起来很有希望),但我还没有研究过。
  • 嗯...没有人能给我更好的答案,这是一个很好的答案。
猜你喜欢
  • 1970-01-01
  • 2020-06-14
  • 2020-08-30
  • 1970-01-01
  • 2019-04-18
  • 2010-10-07
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多