Matplotlib: Getting subplots to fill figure

前端 未结 3 1428
囚心锁ツ
囚心锁ツ 2020-12-11 17:35

I would please like suggestions for how to override the default matplotlib behaviour when plotting images as subplots, whereby the subplot sizes don\'t seem to match the fig

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 17:54

    You can adjust your axis area by using the ax.set_position method. It works with relative coordinates, so if you want to make an A4 image, then:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # figsize keyword talks some obscure units which need a conversion from standard units
    plt.figure(figsize=np.array([210,297]) / 25.4)
    
    x = np.linspace(0,2*np.pi, 100)
    plt.plot(x, np.sin(x))
    
    plt.gca().set_position([0, 0, 1, 1])
    
    plt.show()
    

    Now the axis area (plot area) fills the whole page.

    The coordinates given to the set_position are relative coordinates [left, lower, width, height], where each direction is scaled by the page size.

    As pointed out in the other answers, imshow and matshow try sometimes to keep the pixels in the picture square. There is a rather special interplay with the axis ratio and imshow.

    • if imshow is called without extent=[...] or aspect='auto' keyword arguments, it does what is instructed in the local defaults, usually tries to keep the pixels square
    • if this happens (or aspect='equal' is set), the axes act as if plt.axis('scaled') had been called, i.e. keeps X and Y coordinates equal length (pixels per unit) and change the axis size to match the extents
    • this can be overridden by setting plt.axis('tight') (which makes the x and y limits to fit the image exactly)

    Th old trick is to use axis('auto') or axis('normal'), but these are nowadays deprecated (use scaled, equal, or tight).

    Yes, it is a bit of a mess.

提交回复
热议问题