【问题标题】:Unable to plot 4 histograms of iris dataset features using matplotlib无法使用 matplotlib 绘制 4 个虹膜数据集特征的直方图
【发布时间】:2017-08-17 04:25:14
【问题描述】:

使用虹膜数据集

import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib
from sklearn import datasets
iris= datasets.load_iris()

x_index = 3
colors = ['blue', 'red', 'green']

for label, color in zip(range(len(iris.target_names)), colors):
    plt.hist(iris.data[iris.target==label, x_index], 
                     label=iris.target_names[label],
                                        color=color)

plt.xlabel(iris.feature_names[x_index])
plt.legend(loc='upper right')
plt.show()

enter image description here

此代码仅绘制一个以萼片长度(附图像)为 x 轴的直方图。 要以类似方式绘制 iris 数据集的其他特征,我必须将 x_index 更改为 1,2 和 3(手动)并再次运行这段代码。

为了同时绘制所有四个直方图,我尝试了以下代码:

import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib
from sklearn import datasets
iris= datasets.load_iris()

fig, axes = plt.subplots(nrows= 2, ncols=2)
colors= ['blue', 'red', 'green', 'black']

x_index= 0

for ax in axes.flat:
    for label, color in zip(range(len(iris.target_names)), colors):
        ax= plt.hist(iris.data[iris.target==label, x_index], label=             
                            iris.target_names[label], color=color)
        plt.xlabel(iris.feature_names[x_index])  
        plt.legend(loc='upper right')
        x_index+=1

plt.show()

这段代码给了我以下错误:

IndexError: 索引 4 超出轴 1 的范围,大小为 4

有什么建议吗?

【问题讨论】:

    标签: python-3.x matplotlib


    【解决方案1】:

    两个问题:

    1. ax 是循环中当前坐标区的名称。您不应该重新定义而是使用它,因为这是您要绘制的轴。将ax = plt.hist 替换为ax.hist
    2. x_index+=1 需要在外循环中,而不是在内循环中。否则它将增加到 11 而不是 3。最好完全摆脱它并使用正常的循环变量。

    完整代码:

    import matplotlib.pyplot as plt
    from sklearn import datasets
    iris= datasets.load_iris()
    
    fig, axes = plt.subplots(nrows= 2, ncols=2)
    colors= ['blue', 'red', 'green']
    
    for i, ax in enumerate(axes.flat):
        for label, color in zip(range(len(iris.target_names)), colors):
            ax.hist(iris.data[iris.target==label, i], label=             
                                iris.target_names[label], color=color)
            ax.set_xlabel(iris.feature_names[i])  
            ax.legend(loc='upper right')
    
    
    plt.show()
    

    【讨论】:

    • 颜色用于标签 - ['setosa', 'versicolor', 'virginica']。我需要每个直方图来绘制虹膜数据集的每个特征并按颜色分隔每个标签。这就是为什么我有三种颜色。
    • 好吧,如果您不显示问题的minimal reproducible example,怎么会有人知道?您期望得到什么答案?
    • 我已经编辑了这个问题,以便更清楚地解决我的疑问。您的任何建议都会很棒。谢谢
    • 好的,现在我们有一个minimal reproducible example 可用,解决起来相当简单。查看更新的答案。
    • 谢谢。这很有帮助
    猜你喜欢
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2013-11-26
    • 1970-01-01
    • 2016-06-09
    • 2015-10-25
    相关资源
    最近更新 更多