Search code examples
pythonmatlabmatplotlibpositionaxes

Port Matlab code involving matplotlib setting axes position in pixels


I would need to port this code from matlab to python:

fig;
stringNumber = '0.1'
set(gca,'units','pixels','position',[1 1 145 55],'visible','on')
box('on')

The above code results in the following figure matlabTest1 (screen maximized).

Note that the axes don't scale if the figure is resized, see matlabTest2

I've tried porting it in python converting the position and offset from transFigure to Display / Pixel.

Here's my code:


import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca()
inv = fig.transFigure.inverted()
offset = inv.transform((1, 1))
position = inv.transform((145, 55))
ax.set_position([offset[0], offset[1], position[0],position[1]])
plt.show()

My code results in pythonTest1 (screen maximized). The box size looks different from matlabTest1.

Also if I resize the figure, the box changes in size, see pythonTest2

How can I obtain the exact same result as the matlab code?

Thanks to anyone that can help with this.


Solution

  • Matplotlib figures are positionned in figure coordinates by default. Hence there is no direct equivalent to the matlab code provided.

    One way of specifying the position of the axes in pixels would be to use a AnchoredSizeLocator from mpl_toolkits.axes_grid1.inset_locator.

    import matplotlib.transforms as mtrans
    import mpl_toolkits.axes_grid1.inset_locator as ins
    import matplotlib.pyplot as plt
    
    axes_locator = ins.AnchoredSizeLocator([1, 1, 145, 55],
                                           "100%", "100%",
                                           loc="center",
                                           bbox_transform=mtrans.IdentityTransform(),
                                           borderpad=0)
    
    
    fig, ax = plt.subplots()
    ax.set_axes_locator(axes_locator)
    
    plt.show()