matplotlib画子图报错IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

文章讲述了在使用matplotlib创建子图时遇到的IndexError:数组维度过多,原因是一维数组axs被误认为二维。解决方案是直接使用一维索引访问子图,如axs[0]而非axs[0,0]。
摘要由CSDN通过智能技术生成

matplotlib画子图报错:

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

出现的 IndexError 错误表明你尝试以二维数组的方式访问一个一维数组。在你的代码中,由于你创建的子图网格只有一行(plt.subplots(1, 3, …)),axs 数组实际上是一维的。因此,当你尝试使用 axs[0, 0] 来访问子图时,Python 报告了一个索引错误,因为对于一维数组,只需要一个索引

要修正这个问题,你应该直接使用一维索引来访问 axs 中的子图,如 axs[0] 而不是 axs[0, 0]。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
非常抱歉,我之前的代码中存在问题。以下是已经修改的代码: ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.cluster import KMeans import pyswarms as ps # 加载iris数据集 iris = load_iris() X = iris.data # Kmeans算法聚类 kmeans = KMeans(n_clusters=3, random_state=0) kmeans.fit(X) labels = kmeans.labels_ centroids = kmeans.cluster_centers_ # 定义PSO-Kmeans算法 def objective_function(centroids, X): kmeans = KMeans(n_clusters=len(centroids), init=centroids, n_init=1) kmeans.fit(X) inertia = kmeans.inertia_ return inertia def pso_kmeans(n_particles, n_iterations, X): options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9} bounds = (np.min(X, axis=0), np.max(X, axis=0)) optimizer = ps.single.GlobalBestPSO(n_particles=n_particles, dimensions=X.shape[1], options=options, bounds=bounds) cost, centroids = optimizer.optimize(objective_function, iters=n_iterations, X=X) return cost, centroids # PSO-Kmeans算法聚类 n_particles = 10 n_iterations = 100 cost, centroids_pso = pso_kmeans(n_particles, n_iterations, X) # 可视化结果 fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=labels) ax.scatter(centroids[:, 0], centroids[:, 1], centroids[:, 2], marker='*', s=200, c='#050505') ax.scatter(centroids_pso[0], centroids_pso[1], centroids_pso[2], marker='*', s=200, c='#ff0000') ax.set_xlabel('Sepal Length') ax.set_ylabel('Sepal Width') ax.set_zlabel('Petal Length') plt.show() ``` 这段代码可以在Python环境中运行,使用iris数据集进行聚类,并将Kmeans和PSO-Kmeans的结果可视化。如果您还有任何疑问,请随时联系我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI1.0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值