简体   繁体   中英

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

So I had this:

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")

Which worked fine, but once I ran it on a different VPS (yes, i've already installed all the dependencies with pip), but then it gave me a type error, stating that in plt.plot, countList needed to be float, so I changed the code to this:

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")

But then it gave me this error:

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

so I added xarray = np.asarray(xarray) and fixedList = np.asarray(fixedList) but it still gives me the shape error. What am I doing wrong?

Of course you need to make sure that countList and xarray have the same number of elements. Assuming this to be the case, the problem is that you create an empty list in each loop iteration and append a single element to it. In the next iteration you recreate an empty list, again adding a single element.

Instead you need to create the fixedList outside the loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM