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
. DF
and 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.
Indeed, you have to put fig, ax = plt.subplots()
out of the loop.
A few other things:
edgecolor=''
that way might raise an error. Remove it, or add a specific color.try
and except KeyError
is relevant in your code. Python raises a KeyError whenever a dict() object is requested (using the format a = 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.