jrsm
jrsm

Reputation: 1695

Adjust figure size with respect to the axes size?

Let's say I create a simple plot with matplotlib

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

plot stuff etc .. . 

After I finished the plotting routines I want to adjust the size of my figure (but keeping all aspect ratios the same), such that the total height of ax is set to a constant value i.e. 3 inches. Is there a nice and short way to archieve this ?

EDIT: I know how to change the figure size, but here i want to adjust it according to the size of the axes.

Upvotes: 2

Views: 3451

Answers (1)

HYRY
HYRY

Reputation: 97261

Here is the function to set figure height in inch unit:

def set_axes_height(ax, h):
    fig = ax.figure
    aw, ah = np.diff(ax.transAxes.transform([(0, 0), (1, 1)]), axis=0)[0]
    fw, fh = fig.get_size_inches()
    dpi = fig.get_dpi()
    scale = h / (ah / dpi)
    fig.set_size_inches(fw*scale, fh*scale, forward=True)

Upvotes: 5

Related Questions