How to obtain a fixed height in pixels, fixed data x/y aspect ratio and automatically remove remove horizontal whitespace margin in Matplotlib?

后端 未结 2 432
情深已故
情深已故 2020-12-21 23:32

Let\'s take this as a starting point based on: Specifying and saving a figure with exact size in pixels

#!/usr/bin/env python3

import sys

import numpy as np         


        
2条回答
  •  我在风中等你
    2020-12-22 00:01

    I don't know if I understood your question, but if you want to limit the whitespace in a figure with a 1x2 subplot layout, you simply have to create a figure with a width that's half the height:

    h = 400
    nrows = 2
    w = h/nrows
    dpi = 100
    
    fig, ax = plt.subplots(nrows=nrows, ncols=1, figsize=(w/dpi, h/dpi), dpi=dpi)
    
    t = np.arange(-10., 10., 1.)
    a = ax[0]
    a.set_aspect(1)
    a.plot(t, t, '.')
    a = ax[1]
    a.plot(t, -t, '.')
    a.set_aspect(1)
    plt.tight_layout(pad=1)
    plt.savefig(
        'main.png',
        format='png',
        dpi=dpi,
        facecolor='y',
    )
    

    >> identify main.png

    main.png PNG 200x400 200x400+0+0 8-bit sRGB 6048B 0.000u 0:00.000

提交回复
热议问题