-2

I am trying to plot a histogram here but i keep getting an error

numeric_features = ['tenure', 'MonthlyCharges', 'TotalCharges']

cols = 3
rows = int( np.ceil( len(numeric_features)/ cols))

fig, axes = plt.subplots(rows, cols, figsize=(16,16))

for i in range(len(numeric_features)):
    this_row = int(np.floor(i/cols))
    this_col = int(i%cols)
    feat = numeric_features[i]
    this_ax = axes[this_row][this_col]
    this_ax.hist(df_train[feat], bins=25)
    this_ax.set_title(feat)
 
plt.grid()
plt.show()

It throws the below error:

enter image description here

where am i going wrong here?? i am just trying to plot the numeric values of a dataset.

henryD
  • 21
  • 3
  • For multiple row numbers in subplots, isn't the format `axes[this_row, this_col]`? – r-beginners Nov 08 '21 at 07:08
  • See this [answer](https://stackoverflow.com/a/69228859/7758804): `axes = axes.ravel()` and then see **4.** about zipping an axes to the data, or this [answer](https://stackoverflow.com/a/68793513/7758804) which is specific to dataframes. – Trenton McKinney Nov 08 '21 at 09:50

1 Answers1

0

What is happening here is that when you determine the row values, you get 1, and as such, the axes is not an array of lists as you expect them to be, it is instead just a list of axes.

Print out your axes and see for yourself. That can be the best way to debug issues like these. Look at the actual variables where errors are occurring to verify your assumptions about structure or type are actually correct. Your method works only for when rows > 1.

I'll leave you to work out an approach to account for the case when rows = 1 but feel free to respond and I (or anyone else) can offer more advice.

fam-woodpecker
  • 500
  • 2
  • 10