Matplotlib f、 axes=plt.subplot()和sns.distplot

Matplotlib f、 axes=plt.subplot()和sns.distplot,matplotlib,seaborn,Matplotlib,Seaborn,我看到一篇关于从Seaborn palette()更改颜色的帖子,并试图从答案中理解代码。以下是从@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.r

我看到一篇关于从Seaborn palette()更改颜色的帖子,并试图从答案中理解代码。以下是从@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()
但是,当我尝试通过将plt.subplots行替换为

f, axes = plt.subplots(ncols=3, nrows=2, figsize=(15, 8))
我有一个错误:

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

我做了一些阅读,试图弄清楚plt.subplot()是如何工作的,并从以下示例中找到了一些很好的解释:。然而,我仍然不理解这个错误。这与“轴”(ax=ax)有关吗?

对于(n,rat),zip中的ax(df.groupby(“rating”),axes.ravel()):
当有多列多行时,
轴将是一个2D数组(例如
2x3
axes.ravel()
将其转换为1D数组(例如,一个由6个轴组成的数组)。感谢您对该问题的良好解释和解决方案!:)