簡體   English   中英

輸入錯誤,然后輸入值錯誤:x 和 y 必須具有相同的第一維

[英]Type error, and then ValueError: x and y must have same first dimension

所以我有這個:

def graph_data(dateList, countList, name):
xarray = [0,1,2,3,4,5,6]
xarray = np.asarray(xarray)
myticks = dateList
plt.figure(figsize=(9,5))
plt.xticks(xarray, myticks)
plt.plot(xarray, countList, color='r', linewidth='3.0')
plt.ylabel("Activity")
plt.xlabel("Date")
plt.title(name + "'s Activity for the past 7 days")
plt.savefig("graph.png")

效果很好,但是一旦我在不同的 VPS 上運行它(是的,我已經用 pip 安裝了所有依賴項),但是它給了我一個類型錯誤,指出在 plt.plot 中,countList 需要是浮動的,所以我把代碼改成這樣:

def graph_data(dateList, countList, name):
for n in countList:
    fixedList = []
    fixedList.append(float(n))
xarray = [0,1,2,3,4,5,6]
myticks = dateList
plt.figure(figsize=(9,5))
plt.xticks(xarray, myticks)
plt.plot(xarray, fixedList, color='r', linewidth='3.0')
plt.ylabel("Activity")
plt.xlabel("Date")
plt.title(name + "'s Activity for the past 7 days")
plt.savefig("graph.png")

但后來它給了我這個錯誤:

 "have shapes {} and {}".format(x.shape, y.shape))
 ValueError: x and y must have same first dimension, but have shapes (7,) and (1,)

所以我添加了xarray = np.asarray(xarray)fixedList = np.asarray(fixedList)但它仍然給了我形狀錯誤。 我究竟做錯了什么?

當然,您需要確保countListxarray具有相同數量的元素。 假設是這種情況,問題是您在每次循環迭代中創建一個空列表並向其附加一個元素。 在下一次迭代中,您重新創建一個空列表,再次添加一個元素。

相反,您需要在循環外創建fixedList

fixedList = []
for n in countList:
    fixedList.append(float(n)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM