简体   繁体   English

for 循环中的子图

[英]Subplots within a for-loop

I want to create subplots within a loop, but the outcome is not excactly what I imagined.我想在循环中创建子图,但结果并不是我想象的那样。 I want scatter plots in one big plot. The data originates from the matching columns of two dataframes DF and dfr .我想要一个大 plot 中的散点图。数据来自两个数据帧DFdfr的匹配列。 DF and dfr have the same amount of rows columns and indexes. DFdfr具有相同数量的行列和索引。 The first two columns of both dataframes should be excluded.应排除两个数据框的前两列。

This is my approach, but I get i plots with one subplot each.这是我的方法,但我得到了i的情节,每个情节都有一个子情节。 What am I missing?我错过了什么?

        measurements = 9
        for i in range(2,measurements+1):
            try:
                x = DF.iloc[1:,i]
                y = dfr.iloc[1:,i]
        
                inds = ~np.logical_or(np.isnan(x), np.isnan(y))
                x = x[inds]
                y = y[inds]

                xy = np.vstack([x,y])
                z = gaussian_kde(xy)(xy)
                b, m = polyfit(x, y, 1)
                
                fig, ax = plt.subplots(measurements+1,facecolor='w', edgecolor='k')
                ax[i].scatter(x, y, c=z,  s=50, cmap='jet', edgecolor='', label=None, picker=True, zorder= 2)
                ax[i].plot(x, b + m * x, '-')
      
            except KeyError:
                continue
        plt.show()

Currently I get several plots, but i would like to have one with multipile subplots.目前我有几个地块,但我想要一个有多个子地块的地块。

在此处输入图像描述 在此处输入图像描述

Indeed, you have to put fig, ax = plt.subplots() out of the loop.实际上,您必须将fig, ax = plt.subplots()置于循环之外。

A few other things:其他一些事情:

  • Setting edgecolor='' that way might raise an error.以这种方式设置edgecolor=''可能会引发错误。 Remove it, or add a specific color.删除它,或添加特定颜色。
  • I am sure if using try and except KeyError is relevant in your code.我确定使用try and except KeyError是否与您的代码相关。 Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key] ) and the key is not in the dictionary.每当请求 dict() object(使用格式a = adict[key] )并且键不在字典中时,Python 会引发 KeyError。 Maybe for: x = x[inds] ?也许是为了: x = x[inds] if so, I would suggest do this check earlier in your process.如果是这样,我建议您在您的过程中尽早进行此检查。

Try this:尝试这个:

measurements = 9

fig, ax = plt.subplots(measurements+1, facecolor='w', edgecolor='k')

for i in range(2, measurements+1):
    try:
        x = DF.iloc[1:,i]
        y = dfr.iloc[1:,i]

        inds = ~np.logical_or(np.isnan(x), np.isnan(y))
        x = x[inds]
        y = y[inds]

        xy = np.vstack([x,y])
        z = stats.gaussian_kde(xy)(xy)
        b, m = np.polyfit(x, y, 1)
        ax[i].scatter(x, y, c=z,  s=50, cmap='jet', label=None, picker=True, zorder= 2)
        ax[i].plot(x, b + m * x, '-')
    except KeyError:
        # Temporarily pass but ideally, do something
        pass

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM