matchifang
matchifang

Reputation: 5450

How to expand matplolib window without stretching the plot?

I want to increase the grey area around the plot, but keeping the plot the same size. I've already tried changing the figure size, which ends up stretching the plot. enter image description here

Upvotes: 0

Views: 856

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339340

The axes inside the figure is positionned relative to the figure. Per default you have e.g. a fraction of 0.125 of figure width as space at the left. This means that resizing the figure, scales the axes as well.

You may calculate how much the spacings need to change such that if the figure is rescaled, the axes size remains constant. The new spacings then need to be set using fig.subplots_adjust.

import matplotlib.pyplot as plt

def set_figsize(figw,figh, fig=None):
    if not fig: fig=plt.gcf()
    w, h = fig.get_size_inches()
    l = fig.subplotpars.left
    r = fig.subplotpars.right
    t = fig.subplotpars.top
    b = fig.subplotpars.bottom
    hor = 1.-w/float(figw)*(r-l)
    ver = 1.-h/float(figh)*(t-b)
    fig.subplots_adjust(left=hor/2., right=1.-hor/2., top=1.-ver/2., bottom=ver/2.)

fig, ax=plt.subplots()

ax.plot([1,3,2])

set_figsize(9,7)

plt.show()

You may then also use this function to update the subplot params when the figure window is resized.

import matplotlib.pyplot as plt

class Resizer():
    def __init__(self,fig=None):
        if not fig: fig=plt.gcf()
        self.fig=fig
        self.w, self.h = self.fig.get_size_inches()
        self.l = self.fig.subplotpars.left
        self.r = self.fig.subplotpars.right
        self.t = self.fig.subplotpars.top
        self.b = self.fig.subplotpars.bottom

    def set_figsize(self, figw,figh):  
        hor = 1.-self.w/float(figw)*(self.r-self.l)
        ver = 1.-self.h/float(figh)*(self.t-self.b)
        self.fig.subplots_adjust(left=hor/2., right=1.-hor/2., top=1.-ver/2., bottom=ver/2.)

    def resize(self, event):
        figw = event.width/self.fig.dpi
        figh = event.height/self.fig.dpi
        self.set_figsize( figw,figh)

fig, ax=plt.subplots()

ax.plot([1,3,2])

r = Resizer()
cid = fig.canvas.mpl_connect("resize_event", r.resize)

plt.show()

enter image description here

Upvotes: 2

Michael H.
Michael H.

Reputation: 3483

In the window of a matplotlib figure, there's a button called 'Configure subplots' (see below picture, screenshot on Windows 10 with matplotlib version 1.5.2). Try to change the parameters 'left' and 'right'. You can also change these parameters with plt.subplots_adjust(left=..., bottom=..., right=..., top=..., wspace=..., hspace=...).

enter image description here

Upvotes: 0

Related Questions