在轴坐标系中查找matplotlib绘图的范围(包括刻度标签)

8
我需要找到一个绘图区域的范围,包括其相关的艺术家(在这种情况下只有刻度和刻度标签),以轴坐标表示(如matplotlib转换教程中定义)。
背景是我正在自动创建缩略图绘图(如此SO问题),用于大量图表,只有当我可以将缩略图定位在不遮挡原始绘图数据的位置时才会使用。
这是我的当前方法:
1. 创建多个候选矩形进行测试,从原始绘图的右上角开始向左移动,然后从原始绘图的右下角开始向左移动。 2. 对于每个候选矩形: - 使用此SO问题中的代码将矩形的左侧和右侧(以轴坐标表示)转换为数据坐标,以查找矩形将覆盖哪个x数据切片。 - 查找矩形覆盖的数据切片的最小/最大y值。 - 查找矩形在数据坐标中的顶部和底部。 - 使用上述内容确定矩形是否与任何数据重叠。如果没有,则在当前矩形中绘制缩略图绘图,否则继续。
这种方法的问题是轴坐标给出的是轴的范围,从(0,0)(轴的左下角)到(1,1)(右上角),不包括刻度和刻度标签(缩略图绘图没有标题、轴标签、图例或其他艺术家)。
所有图表使用相同的字体大小,但图表具有不同长度的刻度标签(例如1.51.2345 * 10^6),尽管在绘制插图之前已知。是否有一种方法可以将字体大小/点转换为轴坐标?或者,也许有比上面的方法更好的方法(边界框?)。
以下代码实现了上述算法:
import math

from matplotlib import pyplot, rcParams
rcParams['xtick.direction'] = 'out'
rcParams['ytick.direction'] = 'out'

INSET_DEFAULT_WIDTH = 0.35
INSET_DEFAULT_HEIGHT = 0.25
INSET_PADDING = 0.05
INSET_TICK_FONTSIZE = 8


def axis_data_transform(axis, xin, yin, inverse=False):
    """Translate between axis and data coordinates.
    If 'inverse' is True, data coordinates are translated to axis coordinates,
    otherwise the transformation is reversed.
    Code by Covich, from: https://dev59.com/QF4b5IYBdhLWcg3wchbs
    """
    xlim, ylim = axis.get_xlim(), axis.get_ylim()
    xdelta, ydelta = xlim[1] - xlim[0], ylim[1] - ylim[0]
    if not inverse:
        xout, yout = xlim[0] + xin * xdelta, ylim[0] + yin * ydelta
    else:
        xdelta2, ydelta2 = xin - xlim[0], yin - ylim[0]
        xout, yout = xdelta2 / xdelta, ydelta2 / ydelta
    return xout, yout


def add_inset_to_axis(fig, axis, rect):
    left, bottom, width, height = rect
    def transform(coord):
        return fig.transFigure.inverted().transform(
            axis.transAxes.transform(coord))
    fig_left, fig_bottom = transform((left, bottom))
    fig_width, fig_height = transform([width, height]) - transform([0, 0])
    return fig.add_axes([fig_left, fig_bottom, fig_width, fig_height])


def collide_rect((left, bottom, width, height), fig, axis, data):
    # Find the values on the x-axis of left and right edges of the rect.
    x_left_float, _ = axis_data_transform(axis, left, 0, inverse=False)
    x_right_float, _ = axis_data_transform(axis, left + width, 0, inverse=False)
    x_left = int(math.floor(x_left_float))
    x_right = int(math.ceil(x_right_float))
    # Find the highest and lowest y-value in that segment of data.
    minimum_y = min(data[int(x_left):int(x_right)])
    maximum_y = max(data[int(x_left):int(x_right)])
    # Convert the bottom and top of the rect to data coordinates.
    _, inset_top = axis_data_transform(axis, 0, bottom + height, inverse=False)
    _, inset_bottom = axis_data_transform(axis, 0, bottom, inverse=False)
    # Detect collision.
    if ((bottom > 0.5 and maximum_y > inset_bottom) or  # inset at top of chart
           (bottom < 0.5 and minimum_y < inset_top)):   # inset at bottom
        return True
    return False


if __name__ == '__main__':
    x_data, y_data = range(0, 100), [-1.0] * 50 + [1.0] * 50  # Square wave.
    y_min, y_max = min(y_data), max(y_data)
    fig = pyplot.figure()
    axis = fig.add_subplot(111)
    axis.set_ylim(y_min - 0.1, y_max + 0.1)
    axis.plot(x_data, y_data)
    # Find a rectangle that does not collide with data. Start top-right
    # and work left, then try bottom-right and work left.
    inset_collides = False
    left_offsets = [x / 10.0 for x in xrange(6)] * 2
    bottom_values = (([1.0 - INSET_DEFAULT_HEIGHT - INSET_PADDING] * (len(left_offsets) / 2))
                     + ([INSET_PADDING * 2] * (len(left_offsets) / 2)))
    for left_offset, bottom in zip(left_offsets, bottom_values):
        # rect: (left, bottom, width, height)
        rect = (1.0 - INSET_DEFAULT_WIDTH - left_offset - INSET_PADDING,
                bottom, INSET_DEFAULT_WIDTH, INSET_DEFAULT_HEIGHT)
        inset_collides = collide_rect(rect, fig, axis, y_data)
        print 'TRYING:', rect, 'RESULT:', inset_collides
        if not inset_collides:
            break
    if not inset_collides:
        inset = add_inset_to_axis(fig, axis, rect)
        inset.set_ylim(axis.get_ylim())
        inset.set_yticks([y_min, y_min + ((y_max - y_min) / 2.0), y_max])
        inset.xaxis.set_tick_params(labelsize=INSET_TICK_FONTSIZE)
        inset.yaxis.set_tick_params(labelsize=INSET_TICK_FONTSIZE)
        inset_xlimit = (0, int(len(y_data) / 100.0 * 2.5)) # First 2.5% of data.
        inset.set_xlim(inset_xlimit[0], inset_xlimit[1], auto=False)
        inset.plot(x_data[inset_xlimit[0]:inset_xlimit[1] + 1],
                   y_data[inset_xlimit[0]:inset_xlimit[1] + 1])
    fig.savefig('so_example.png')

这个的输出结果是:
TRYING: (0.6, 0.7, 0.35, 0.25) RESULT: True
TRYING: (0.5, 0.7, 0.35, 0.25) RESULT: True
TRYING: (0.4, 0.7, 0.35, 0.25) RESULT: True
TRYING: (0.30000000000000004, 0.7, 0.35, 0.25) RESULT: True
TRYING: (0.2, 0.7, 0.35, 0.25) RESULT: True
TRYING: (0.10000000000000002, 0.7, 0.35, 0.25) RESULT: False

script output

2个回答

5

我的解决方案似乎无法检测刻度标记,但是可以处理刻度标签、轴标签和图表标题。希望这已经足够了,因为一个固定的填充值应该足以考虑到刻度标记。

使用axes.get_tightbbox获取一个矩形,该矩形适合包含标签的轴。

from matplotlib import tight_layout
renderer = tight_layout.get_renderer(fig)
inset_tight_bbox = inset.get_tightbbox(renderer)

相比于您的原始矩形设置坐标轴 bbox,inset.bbox。在这两个 bbox 中找到以轴坐标为基准的矩形:

inv_transform = axis.transAxes.inverted() 

xmin, ymin = inv_transform.transform(inset.bbox.min)
xmin_tight, ymin_tight = inv_transform.transform(inset_tight_bbox.min) 

xmax, ymax = inv_transform.transform(inset.bbox.max)
xmax_tight, ymax_tight = inv_transform.transform(inset_tight_bbox.max)

现在为轴本身计算一个新的矩形,使得外部紧密边界框的大小缩小到旧的轴边界框大小:
xmin_new = xmin + (xmin - xmin_tight)
ymin_new = ymin + (ymin - ymin_tight)
xmax_new = xmax - (xmax_tight - xmax)
ymax_new = ymax - (ymax_tight - ymax)     

现在,只需切换回图形坐标并重新定位插入轴:
[x_fig,y_fig] = axis_to_figure_transform([xmin_new, ymin_new])
[x2_fig,y2_fig] = axis_to_figure_transform([xmax_new, ymax_new])

inset.set_position ([x_fig, y_fig, x2_fig - x_fig, y2_fig - y_fig])

axis_to_figure_transform函数基于您在add_inset_to_axis中所使用的transform函数:

def axis_to_figure_transform(coord, axis):
    return fig.transFigure.inverted().transform(
        axis.transAxes.transform(coord))

注意:这个方法在我的系统上不能与fig.show()一起使用;tight_layout.get_renderer(fig)会导致错误。然而,如果你只是使用savefig()而不是交互地显示图形,它就能正常工作。
最后,以下是带有我的修改和补充的完整代码:
import math

from matplotlib import pyplot, rcParams, tight_layout
rcParams['xtick.direction'] = 'out'
rcParams['ytick.direction'] = 'out'

INSET_DEFAULT_WIDTH = 0.35
INSET_DEFAULT_HEIGHT = 0.25
INSET_PADDING = 0.05
INSET_TICK_FONTSIZE = 8

def axis_data_transform(axis, xin, yin, inverse=False):
    """Translate between axis and data coordinates.
    If 'inverse' is True, data coordinates are translated to axis coordinates,
    otherwise the transformation is reversed.
    Code by Covich, from: https://dev59.com/QF4b5IYBdhLWcg3wchbs
    """
    xlim, ylim = axis.get_xlim(), axis.get_ylim()
    xdelta, ydelta = xlim[1] - xlim[0], ylim[1] - ylim[0]
    if not inverse:
        xout, yout = xlim[0] + xin * xdelta, ylim[0] + yin * ydelta
    else:
        xdelta2, ydelta2 = xin - xlim[0], yin - ylim[0]
        xout, yout = xdelta2 / xdelta, ydelta2 / ydelta
    return xout, yout

def axis_to_figure_transform(coord, axis):
    return fig.transFigure.inverted().transform(
        axis.transAxes.transform(coord))

def add_inset_to_axis(fig, axis, rect):
    left, bottom, width, height = rect

    fig_left, fig_bottom = axis_to_figure_transform((left, bottom), axis)
    fig_width, fig_height = axis_to_figure_transform([width, height], axis) \
                                   - axis_to_figure_transform([0, 0], axis)
    return fig.add_axes([fig_left, fig_bottom, fig_width, fig_height], frameon=True)


def collide_rect((left, bottom, width, height), fig, axis, data):
    # Find the values on the x-axis of left and right edges of the rect.
    x_left_float, _ = axis_data_transform(axis, left, 0, inverse=False)
    x_right_float, _ = axis_data_transform(axis, left + width, 0, inverse=False)
    x_left = int(math.floor(x_left_float))
    x_right = int(math.ceil(x_right_float))
    # Find the highest and lowest y-value in that segment of data.
    minimum_y = min(data[int(x_left):int(x_right)])
    maximum_y = max(data[int(x_left):int(x_right)])
    # Convert the bottom and top of the rect to data coordinates.
    _, inset_top = axis_data_transform(axis, 0, bottom + height, inverse=False)
    _, inset_bottom = axis_data_transform(axis, 0, bottom, inverse=False)
    # Detect collision.
    if ((bottom > 0.5 and maximum_y > inset_bottom) or  # inset at top of chart
           (bottom < 0.5 and minimum_y < inset_top)):   # inset at bottom
        return True
    return False


if __name__ == '__main__':
    x_data, y_data = range(0, 100), [-1.0] * 50 + [1.0] * 50  # Square wave.
    y_min, y_max = min(y_data), max(y_data)
    fig = pyplot.figure()
    axis = fig.add_subplot(111)
    axis.set_ylim(y_min - 0.1, y_max + 0.1)
    axis.plot(x_data, y_data)
    # Find a rectangle that does not collide with data. Start top-right
    # and work left, then try bottom-right and work left.
    inset_collides = False
    left_offsets = [x / 10.0 for x in xrange(6)] * 2
    bottom_values = (([1.0 - INSET_DEFAULT_HEIGHT - INSET_PADDING] * (len(left_offsets) / 2))
                     + ([INSET_PADDING * 2] * (len(left_offsets) / 2)))
    for left_offset, bottom in zip(left_offsets, bottom_values):
        # rect: (left, bottom, width, height)
        rect = (1.0 - INSET_DEFAULT_WIDTH - left_offset - INSET_PADDING,
                bottom, INSET_DEFAULT_WIDTH, INSET_DEFAULT_HEIGHT)
        inset_collides = collide_rect(rect, fig, axis, y_data)
        print 'TRYING:', rect, 'RESULT:', inset_collides
        if not inset_collides:
            break
    if not inset_collides:
        inset = add_inset_to_axis(fig, axis, rect)
        inset.set_ylim(axis.get_ylim())
        inset.set_yticks([y_min, y_min + ((y_max - y_min) / 2.0), y_max])
        inset.xaxis.set_tick_params(labelsize=INSET_TICK_FONTSIZE)
        inset.yaxis.set_tick_params(labelsize=INSET_TICK_FONTSIZE)
        inset_xlimit = (0, int(len(y_data) / 100.0 * 2.5)) # First 2.5% of data.
        inset.set_xlim(inset_xlimit[0], inset_xlimit[1], auto=False)
        inset.plot(x_data[inset_xlimit[0]:inset_xlimit[1] + 1],
                   y_data[inset_xlimit[0]:inset_xlimit[1] + 1])


    # borrow this function from tight_layout 
    renderer = tight_layout.get_renderer(fig)
    inset_tight_bbox = inset.get_tightbbox(renderer)

    # uncomment this to show where the two bboxes are
#    def show_bbox_on_plot(ax, bbox, color='b'):
#        inv_transform = ax.transAxes.inverted()
#        xmin, ymin = inv_transform.transform(bbox.min)
#        xmax, ymax = inv_transform.transform(bbox.max)
#        axis.add_patch(pyplot.Rectangle([xmin, ymin], xmax-xmin, ymax-ymin, transform=axis.transAxes, color = color))
#        
#    show_bbox_on_plot(axis, inset_tight_bbox)
#    show_bbox_on_plot(axis, inset.bbox, color = 'g')

    inv_transform = axis.transAxes.inverted() 

    xmin, ymin = inv_transform.transform(inset.bbox.min)
    xmin_tight, ymin_tight = inv_transform.transform(inset_tight_bbox.min) 

    xmax, ymax = inv_transform.transform(inset.bbox.max)
    xmax_tight, ymax_tight = inv_transform.transform(inset_tight_bbox.max)

    # shift actual axis bounds inwards by "margin" so that new size + margin
    # is original axis bounds
    xmin_new = xmin + (xmin - xmin_tight)
    ymin_new = ymin + (ymin - ymin_tight)
    xmax_new = xmax - (xmax_tight - xmax)
    ymax_new = ymax - (ymax_tight - ymax)

    [x_fig,y_fig] = axis_to_figure_transform([xmin_new, ymin_new], axis)
    [x2_fig,y2_fig] = axis_to_figure_transform([xmax_new, ymax_new], axis)

    inset.set_position ([x_fig, y_fig, x2_fig - x_fig, y2_fig - y_fig])

    fig.savefig('so_example.png')

非常感谢您的帮助。当我将其移植到我们原始代码上(此示例基于该代码)时,show() 看起来运行良好。我猜测这是因为我们使用了 PDF 渲染器。顺便说一下,我认为 inset_bbox = inset.bbox.inverse_transformed(axis.transAxes) 这一行可能是多余的,因为 inset_bbox 从未被读取。 - snim2
你说得对,那一行是上一个迭代留下的,现在我已经删除了它以增加清晰度。如果你搜索关于“renderer”的东西,似乎会因为后端的不同而有所不同,特别是在Mac OS上会出现问题。可以尝试使用renderer = fig.canvas.get_renderer()而不是导入tight_layout或回答这个问题。无论如何,如果它已经起作用了,那太好了。很高兴能帮到你! - Ben Schmidt

0

要获取图形坐标中轴线的紧凑边界框,请使用以下方法:

def tight_bbox(ax):
    fig = ax.get_figure()
    tight_bbox_raw = ax.get_tightbbox(fig.canvas.get_renderer())
    from matplotlib.transforms import TransformedBbox
    tight_bbox_fig = TransformedBbox(tight_bbox_raw, fig.transFigure.inverted())
    return tight_bbox_fig

这可以用于将标签相对于图坐标放置在紧密边界框之外。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接