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. DFand dfr have the same amount of rows columns and indexes. The first two columns of both dataframes should be excluded.
This is my approach, but I get i plots with one subplot each. 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.
CodePudding user response:
Indeed, you have to put fig, ax = plt.subplots() out of the loop.
A few other things :
- Setting
edgecolor=''that way might raise an error. Remove it, or add a specific color. - I am sure if using
tryandexcept KeyErroris relevant in your code. Python raises a KeyError whenever a dict() object is requested (using the formata = adict[key]) and the key is not in the dictionary. Maybe for: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()


