将轴添加到具有固定大小的图形中 [英] Add axes to a figure with a fixed size

查看:44
本文介绍了将轴添加到具有固定大小的图形中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个图形,其中在 for 循环中动态添加子图.应该可以以厘米为单位定义每个子图的宽度和高度,即添加的子图越多,图就需要越大,以便为传入"子图腾出空间.

在我的例子中,子图应该逐行添加,这样图形必须在 y 维度上变大.我遇到了这个

I would like to create a figure where subplots are added dynamically within a for-loop. It should be possible to define the width and height of each subplot in centimeters, that is, the more subplots are added, the bigger the figure needs to be to make room for 'incoming' subplots.

In my case, subplots should be added row-wise so that the figure has to get bigger in the y-dimension. I came across this stackoverflow post, which might lead in the right direction? Maybe also the gridspec module could solve this problem?

I tried out the code as described in the first post, but this couldn't solve my problem (it sets the final figure size, but the more subplots are added to the figure the smaller each subplot gets, as shown in this example):

import matplotlib.pyplot as plt

# set number of plots
n_subplots = 2

def set_size(w,h,ax=None):
    """ w, h: width, height in inches """
    if not ax: ax=plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w)/(r-l)
    figh = float(h)/(t-b)
    ax.figure.set_size_inches(figw, figh)

fig = plt.figure()

for idx in range(0,n_subplots):
    ax = fig.add_subplot(n_subplots,1,idx+1)
    ax.plot([1,3,2])
    set_size(5,5,ax=ax)

plt.show()

解决方案

You're setting the same figure size (5,5) regardless of the number of subplots. If I understood your question correctly, I think you want to set the height to be proportional to the number of subplots.

However, you'd be better off to create the figure with the right size from the get-go. The code that you are providing gives the correct layout only because you know before hand how many subplots your going to create (in fig.add_subplot(n_subplots,...)). If you are trying to add subplots without knowing the total number of subplot rows you need, the problem is more complicated.

n_subplots = 4

ax_w = 5
ax_h = 5
dpi = 100

fig = plt.figure(figsize=(ax_w, ax_h), dpi=dpi)

for idx in range(0,n_subplots):
    ax = fig.add_subplot(n_subplots,1,idx+1)
    ax.plot([1,3,2])
fig.set_size_inches(ax_w,ax_h*n_subplots)
fig.tight_layout()

这篇关于将轴添加到具有固定大小的图形中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆