Filip
Filip

Reputation: 1

Error 'AttributeError: 'str' object has no attribute... ' when creating subplots with for-loop

To create subplots (scatter plots of certain features) I have tried via an automated way by using a for loop:

fig, (ax1,ax2) = plt.subplots(1,10) # 1 row, 10 columns

# sample data
for i in range(10):
  x = X1['label_scatter']
  y = X1['feat0_' + str(i)]
  temp = "ax" + str(i)
  temp.scatter(x,y)

But raises an error 'AttributeError: 'str' object has no attribute 'scatter''. I have more than 40 features, how could I peform this operation by an automated way?

Upvotes: 0

Views: 135

Answers (1)

mozway
mozway

Reputation: 260790

Don't try to create variables dynamically. Instead use a container:

fig, axes = plt.subplots(1,10) # 1 row, 10 columns

for i, ax in in enumerate(axes):
  x = X1['label_scatter']
  y = X1[f'feat0_{i}']
  ax.scatter(x,y)
  # or
  # axes[i].scatter(x,y)

Upvotes: 1

Related Questions