【发布时间】: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()
此代码仅绘制一个以萼片长度(附图像)为 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