[英]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.