How to change size of figure with subplots

137.7k Views Asked by At

I'm having some trouble trying to change the figure size when using plt.subplots. With the following code, I just get the standard size graph with all my subplots bunched in (there's ~100) and obviously just an extra empty figuresize . I've tried using tight_layout, but to no avail.

def plot(reader):
    channels=[]
    for i in reader:
        channels.append(i)

    plt.figure(figsize=(50,100))
    fig, ax = plt.subplots(len(channels), sharex=True)
    
    plot=0    
    for j in reader: 
        
        ax[plot].plot(reader["%s" % j])
        plot=plot+1

    plt.tight_layout()
    plt.show()

enter image description here

2

There are 2 best solutions below

1
On BEST ANSWER

You can remove your initial plt.figure(). When calling plt.subplots() a new figure is created, so you first call doesn't do anything.

The subplots command in the background will call plt.figure() for you, and any keywords will be passed along. So just add the figsize keyword to the subplots() command:

def plot(reader):
    channels=[]
    for i in reader:
        channels.append(i)

    fig, ax = plt.subplots(len(channels), sharex=True, figsize=(50,100))

    plot=0    
    for j in reader: 

        ax[plot].plot(reader["%s" % j])
        plot=plot+1

    plt.tight_layout()
    plt.show()
0
On

The figure size is in inches. If for whatever reason, the figsize of subplots needs to be changed after plotting (perhaps because its creation is handled by an external library such as statsmodels etc.), then you can call set_size_inches() on the figure object to set the figure size.

fig.set_size_inches(50, 100)
# or 
plt.gcf().set_size_inches(50, 100)

A working example:

import random
def subplots():
    xs = [[range(3)]*2]*2
    ys = [[[random.random() for _ in range(3)] for _ in range(2)] for _ in range(2)]
    fig, axs = plt.subplots(2,2)
    for i, row in enumerate(zip(xs, ys)):
        for j, (x, y) in enumerate(row):
            axs[i][j].plot(x, y)

subplots()                          # draw subplots
plt.gcf().set_size_inches(15,5)     # set figure size afterwards

Another example where a time series decomposition plot is handled by statsmodels. Without setting figure size post-plotting, the resulting figure is too small:

import random, pandas as pd
from statsmodels.tsa.seasonal import seasonal_decompose

data = pd.Series([random.random() for _ in range(100)], index=pd.date_range('2020', periods=100, freq='D'))
decomp = seasonal_decompose(data)
fig = decomp.plot()
fig.set_size_inches(10,10)
#   ^^^^^^^^^^^^^^^       <---- set figure size to (10, 10)