You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Matplotlib bar()绘制PCA碎石图时提示缺少left参数

解决Matplotlib bar()函数的TypeError问题

嘿,我来帮你搞定这个报错!你遇到的TypeError: bar() missing 1 required positional argument: 'left'是因为Matplotlib版本兼容问题:

问题根源

在Matplotlib 3.0之前的旧版本中,plt.bar()函数用来指定条形位置的参数是left,而你代码里用的是x——这个参数是Matplotlib 3.0及以上版本才引入的简化写法。旧版本不识别x参数,所以会提示缺少必需的left参数。

两种解决方案

方案1:升级Matplotlib(推荐)

直接把Matplotlib升级到3.0或更高版本,这样你的原代码就能正常运行了。在终端里执行以下命令:

pip install --upgrade matplotlib

方案2:修改代码参数

如果暂时不想升级版本,只需要把plt.bar()里的x参数替换成left就行,修正后的完整代码如下:

import pandas as pd 
import numpy as np 
from sklearn.decomposition import PCA 
from sklearn import preprocessing 
import matplotlib.pyplot as plt 

# 确保data是已加载的有效数据集
scaled_data = preprocessing.scale(data.T) 
pca=PCA() 
pca.fit(scaled_data) 
pca_data = pca.transform(scaled_data) 

per_var = np.round(pca.explained_variance_ratio_*100, decimals=1) 
labels = ['PC'+str(i) for i in range(1,len(per_var)+1)] 

# 将x替换为left
plt.bar(left=range(1,len(per_var)+1), height=per_var, tick_label=labels) 
plt.xlabel('Principal Component') 
plt.ylabel('Percentage of Variance Explained') 
plt.title('Scree Plot') 
plt.show()

另外小提醒:运行前要确认data变量已经正确加载了你的数据集哦,不然可能会出现其他报错,但当前的问题已经通过上面的方法解决啦!

内容的提问来源于stack exchange,提问作者basil ahamed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:32:36