使用plt.hist()绘制多直方图时出现参数长度不匹配错误求助
问题:plt.hist()绘制多直方图时触发颜色不匹配的ValueError
我定义了check3_pt_bias(x)函数,用plt.hist()绘制多直方图,声明了4个数据集和4种对应颜色。但调用check3_pt_bias(2)时触发ValueError,提示'color'参数需为每个数据集分配一种颜色,但提供了914873个数据集和4种颜色。打印数据集信息显示biahist长度为4,每个元素长度都是914873,且其他x值调用函数能成功运行,求解决思路。
代码示例
def check3_pt_bias(x): bins=[[25,60,90,120,160,400],[25,40,60,400],[25,45,70,100,160,400],[25,35,55,400]] name = ['lead b-top','sub-lead b-top','lead b-Add','sub-lead b-Add'] biahist=np.array([collection42[2][x],collection42[1][x],collection43[1][x],collection44[1][x]],dtype=object) for i in range(len(biahist)): print(len(biahist[i])) print(len(biahist)) fig, axs = plt.subplots(2,1, gridspec_kw={'height_ratios': [2, 1]}) (n, bins, patches)=axs[0].hist(biahist, bins[x],color=['r','g','b','y'], range =[0,400], density=True, histtype='step',label=['truth','All_var model','dR model','Mass model']) axs[0].legend() axs[0].set_ylabel('density') axs[0].set_yscale('log') axs[0].set_xscale('log') axs[0].set(xticklabels=[]) ratio = [[],[],[]] div = [0,0,0] wdiv = [0,0,0] for i in range(len(n[0])): for j in range(3): ratio[j].append(n[j+1][i]/n[0][i]) div[j] += (ratio[j][i]-1)**2 wdiv[j] += ((ratio[j][i]-1)*n[0][i])**2 axs[1].hlines(y = ratio[0][i], xmin = bins[i], xmax = bins[i+1],color = 'g',label='All_var model') axs[1].hlines(y = ratio[1][i], xmin = bins[i], xmax = bins[i+1],color = 'b',label='dR model') axs[1].hlines(y = ratio[2][i], xmin = bins[i], xmax = bins[i+1],color = 'y',label='Mass model') axs[1].hlines(y = 1, xmin = bins[0], xmax = bins[-1],color = 'r',label='truth') axs[1].set_xlabel('Pt ('+name[x]+'), GeV') axs[1].set_ylabel('model / truth') #plt.show() print("deviation of All_var model:",np.sqrt(div[0])) print("deviation of dR model:",np.sqrt(div[1])) print("deviation of Mass model:",np.sqrt(div[2])) print("weighted deviation of All_var model:",np.sqrt(wdiv[0])) print("weighted deviation of dR model:",np.sqrt(wdiv[1])) print("weighted deviation of Mass model:",np.sqrt(wdiv[2])) check3_pt_bias(2)
运行输出
914873 914873 914873 914873 4 ValueError: The 'color' keyword argument must have one color per dataset, but 914873 datasets and 4 colors were provided
解决思路与修复方法
问题根源
plt.hist()对输入数据的维度解析逻辑导致:当你用np.array(..., dtype=object)包装4个长度相同的数组时,numpy会创建一个一维的object数组,但plt.hist()在配合x=2对应的bins参数时,会错误地将这个数组解析为914873个单独的数据集(每个元素一个),而不是4个数据集。其他x值能运行是因为对应的bins长度刚好让解析逻辑正常工作。
修复步骤
直接将biahist改为Python列表,避免使用numpy object数组:
# 原代码 # biahist=np.array([collection42[2][x],collection42[1][x],collection43[1][x],collection44[1][x]],dtype=object) # 修改后 biahist = [collection42[2][x], collection42[1][x], collection43[1][x], collection44[1][x]]
原理说明
plt.hist()原生支持接收列表形式的多个数据集,每个列表元素对应一个直方图系列。改用Python列表后,函数会正确识别这是4个数据集,与你提供的4种颜色一一对应,不会出现解析错误。
内容的提问来源于stack exchange,提问作者GeoLouise
相关产品推荐
相关产品推荐

