Matplotlib绘制多线图报错:x与y维度不匹配原因咨询
Matplotlib绘图维度不匹配错误分析
代码示例
import matplotlib.pyplot as plt import pandas as pd data1 = csv.reader(open('data.csv', encoding = 'cp949')) next(data1) year = [] preference = [] for i in range(8): preference.append([]) for i in range(2015, 2022): year.append(i) for row in data1: for i in range(8): preference[i].append(float(row[i+3])) plt.plot(year, preference) plt.title('preference') plt.xlabel('year') plt.ylabel('percent(%)')
运行报错
x and y must have same first dimension, but have shapes (7,) and (8, 7)
疑问
year列表有7个元素,preference里每个子列表也都是7个元素,按说x和y的维度应该匹配,为啥会报错?
错误原因
问题出在你对plt.plot()参数格式的理解上:
- 你传入的
year是长度为7的一维列表(形状(7,)),而preference是包含8个一维子列表的二维列表(形状(8,7))。 - Matplotlib处理二维y参数时,要求y的第二维度和x的长度一致,而不是第一维度。现在
preference的第一维度是8,和x的7不匹配,所以触发报错。 - 你要实现的是画8条曲线,每条对应preference里的一个子列表,正确的做法有两种:
- 把preference转置,让它变成形状
(7,8)的结构,这样第二维度8对应每条曲线,第一维度7和year长度匹配:plt.plot(year, list(zip(*preference))) - 循环遍历preference里的每个子列表,单独绘制每条曲线:
for p in preference: plt.plot(year, p)
- 把preference转置,让它变成形状
另外提一句:你的代码里没导入csv模块,实际运行会先报NameError: name 'csv' is not defined,记得补上import csv。
内容的提问来源于stack exchange,提问作者jiyoon jang
相关产品推荐
相关产品推荐

