Matplotlib: image.get_window_extent (renderer) creates all zeros

I find the get_window_extent method for the image object gives all zeros.

for example

import numpy as np
import matplotlib.pyplot as plt

im = np.array([[0.25, 0.75, 1.0, 0.75], [0.1, 0.65, 0.5, 0.4], \
    [0.6, 0.3, 0.0, 0.2], [0.7, 0.9, 0.4, 0.6]])
fig = plt.figure()
ax = plt.subplot()
ax.set_xlim(0,1)
ax.set_ylim(0,1)
im_obj = ax.imshow(im, extent = [0.25, 0.75, 0.25, 0.75], interpolation = 'nearest')

displays the following graph

image

Now I want to get the image size in display coordinates, so I do the following:

fig.canvas.draw()
renderer = fig.canvas.renderer
im_bbox = im_obj.get_window_extent(renderer)

The problem print im_bboxis causing Bbox('array([[ 0., 0.],\n [ 0., 0.]])'). The method .get_window_extent(renderer)works fine with text, lines and patches, so I was a little surprised to see that it does not work with images. Is this a mistake, or am I doing something wrong?

In case that matters, I use Matplotlib 1.3.0 with the TkAgg backend.


EDIT:

Here is the work to get the frame of the image in the displayed coordinates

im_ext = im_obj.get_extent()
im_pts = np.array([[im_ext[0], im_ext[2]], [im_ext[1], im_ext[3]]])
bbox = mpl.transforms.Bbox(im_pts)
fig.canvas.draw()
bbox = bbox.transformed(ax.transData)

Now print bboxcreates Bbox('array([[ 236.375, 148.2 ],\n [ 433.975, 345.8 ]])'). I also confirmed that these values ​​are correct. The following code:

from matplotlib.patches import Rectangle
rect = Rectangle([bbox.x0, bbox.y0], \
    bbox.width, bbox.height, \
    linewidth = 8, color = [1,0,0], \
    fill = False)
fig.patches.append(rect)
fig.canvas.draw()
plt.savefig('wtf.png', dpi = mpl.rcParams['figure.dpi'])

displays the following graph

whew

, . , , fig.canvas.draw(), (). fig.canvas.draw() . , matplotlib , , .

, . im_obj.get_window_extent(renderer) ?

+4
1

, , , , ( draw()) , , . , matplotlib , .

, , , mpl , tight_layout .

+3

Source: https://habr.com/ru/post/1536245/


All Articles