Adjust figure size with respect to the axes size?

梦想的初衷 提交于 2021-01-29 07:05:33

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/34675439/adjust-figure-size-with-respect-to-the-axes-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!