0

I saw a post about changing colors from Seaborn palette (Selecting colors from Seaborn palette), and tried to understand the codes from the answer. Here are the codes copied from @ImportanceOfBeingErnest:

import matplotlib.pyplot as plt
import seaborn as sns; sns.set(style="white")
import pandas as pd
import numpy as np

df = pd.DataFrame({"cost" : np.random.randn(600),
                   "rating" : np.random.choice(np.arange(1,6), size=600)})

ratings = np.unique(df.rating.values)
palette = iter(sns.husl_palette(len(ratings)))

f, axes = plt.subplots(ncols=len(ratings), figsize=(15, 4))
sns.despine(left=True)

for (n, rat), ax in zip(df.groupby("rating"), axes):

    sns.distplot(rat["cost"], kde=False, color=next(palette), ax=ax, axlabel=f"Rating of {n}")

plt.setp(axes, yticks=[])
plt.tight_layout()
plt.show()

However, when I try to make a plot with 2 rows by replacing the plt.subplots line to

f, axes = plt.subplots(ncols=3, nrows=2, figsize=(15, 8))

I've got an error:

AttributeError: 'numpy.ndarray' object has no attribute 'hist'

I've done some readings and tried to figure out how plt.subplots() works, and found some good explanations from for example here: Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python. However, I still don't understand the error. Is it something to do with the "axes" (ax=ax)?

Nina
  • 3
  • 3
  • 1
    `for (n, rat), ax in zip(df.groupby("rating"), axes.ravel()):` – BigBen Oct 29 '20 at 20:20
  • 1
    When there are multiple columns *and* multiple rows, `axes` will be a 2D array (e.g.`2x3`). `axes.ravel()` will convert it to a 1D array (e.g. one array of 6 axes). – JohanC Oct 29 '20 at 20:39
  • Thank you both for good explanation and solution of the problem! :) – Nina Oct 30 '20 at 13:56

0 Answers0