Search code examples
pythonmatplotlibfigure

Stretching figure size in a double-y plot


I'm trying to learn how I can stretch the width of my plot both when showing (plt.show()) it and saving (plt.savefig) it.

More precisely, the plot has two y-axes that I have written as follows:

fig , ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x,y)
ax2.plot(x,y2)
plt.show()

Now the question is, how can I specify the size of the plot, e.g., how do we stretch the width/height? When using plt.show() and the plot appears, I can manually take one corner and resize the box however desired, but that manually customised size will not be the saved one.


Solution

  • You can set the figure size ratio with figsize=(width, height)

    import matplotlib.pyplot as plt
    
    x = [1, 2, 3]           # dummy data
    y = [4, 5, 6]
    y2 = [16, 25, 36]
    
    fig , ax1 = plt.subplots(figsize=(7, 2))   # <-- aspect wider than high
    ax2 = ax1.twinx()
    ax1.plot(x,y)
    ax2.plot(x,y2)
    plt.show()