[英]Plotting scatter points with matplotlib from a CSV file question
我已经从网站中提取了一些数据到CSV文件中,并且需要从该CSV文件中在matplotlib中绘制散点图。 我只需要CSV文件中的第2列和第3列数据。
我试图使用一个for循环将CSV数据收集到一个列表中,然后使用它来绘制散点图,但出现“ ValueError:x和y必须为相同大小”错误。
import matplotlib.pyplot as plt
import csv
with open(cache_path + distance_csv) as csv_file:
reader = csv.reader(csv_file)
for column in reader:
city_distance = [x[1] for x in csv.reader(csv_file)]
crime_rate = [x[2] for x in csv.reader(csv_file)]
plt.scatter(city_distance, crime_rate)
plt.show()
CSV文件中的第2列和第3列的长度相同-83个单元格,但出现ValueError。 我在这里想念什么?
您的代码中有一些错误,我不知道是哪个错误导致了您的行为,但是在修复所有错误之后,您可以继续进行:
因此,可能的解决方案是:
import matplotlib.pyplot as plt
import csv
with open(cache_path + distance_csv) as csv_file:
reader = csv.reader(csv_file)
city_distance, crime_rate = [], []
for column in reader:
city_distance.append(float(column[1]))
crime_rate.append(float(column[2]))
plt.scatter(city_distance, crime_rate)
plt.show()
为了将来,我建议您尝试验证len(city_distance)==len(crime_rate)
。 我的意思是,在读取值之后并在错误之前,不检查csv中的数据,而是检查代码中的数据-以获取最有用的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.