如何解决Matplotlib中ValueError: x and y must be the same size错误
解决Matplotlib中
ValueError: x and y must be the same size错误 问题场景
运行以下代码时触发维度不匹配错误:
plt.plot(tag_counts[0:100], c='b') plt.scatter(x=list(range(0,100,5)), y=tag_counts[0:100:5], c='orange', label="quantiles with 0.05 intervals") # quantiles with 0.25 difference plt.scatter(x=list(range(0,100,25)), y=tag_counts[0:100:25], c='m', label = "quantiles with 0.25 intervals") for x,y in zip(list(range(0,100,25)), tag_counts[0:100:25]): plt.annotate(s="({} , {})".format(x,y), xy=(x,y), xytext=(x-0.05, y+500)) plt.legend() plt.show() print(len(tag_counts[0:100:5]), tag_counts[0:100:5])
错误原因
核心问题是切片与x轴序列的长度不匹配:
list(range(0,100,5))固定生成20个元素(0、5、10...95)- 但
tag_counts[0:100:5]的元素数量取决于tag_counts的实际长度,如果原数据长度不足100,切片得到的元素数量会少于20,导致x和y维度不一致
修复后的代码
通过基于实际切片长度生成x轴索引,确保x和y严格对应:
plt.plot(tag_counts[0:100], c='b') # 先截取前100个元素,避免重复操作 top_100_tags = tag_counts[0:100] # 基于实际元素长度生成步长为5的x、y序列 x_step5 = list(range(len(top_100_tags)))[::5] y_step5 = top_100_tags[::5] plt.scatter(x=x_step5, y=y_step5, c='orange', label="间隔0.05的分位点") # 处理步长为25的分位点 x_step25 = list(range(len(top_100_tags)))[::25] y_step25 = top_100_tags[::25] plt.scatter(x=x_step25, y=y_step25, c='m', label="间隔0.25的分位点") # 添加标注 for x,y in zip(x_step25, y_step25): plt.annotate(s="({} , {})".format(x,y), xy=(x,y), xytext=(x-0.05, y+500)) plt.legend() plt.show() print(len(y_step5), y_step5)
关键说明
- 先将
tag_counts[0:100]存入变量,避免重复切片操作 - 用
range(len(top_100_tags))生成与切片长度完全匹配的索引序列,再按步长取数,彻底避免维度不匹配问题 - 无论
tag_counts原长度是否达到100,该逻辑都能正常运行
内容的提问来源于stack exchange,提问作者nes
相关产品推荐
相关产品推荐

