首页 > 解决方案 > f,轴 = plt.subplots() 和 sns.distplot

问题描述

我看到一篇关于从 Seaborn 调色板中更改颜色的帖子(从 Seaborn 调色板中选择颜色),并试图从答案中理解代码。以下是从@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.subplots() 是如何工作的,并从例如这里找到了一些很好的解释:Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/蟒蛇。但是,我仍然不明白这个错误。它与“轴”(ax = ax)有关吗?

标签: matplotlibseaborn

解决方案


推荐阅读