Type error, and then ValueError: x and y must have same first dimension
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)
但它仍然给我形状错误。我做错了什么?
当然需要保证countList
和xarray
的元素个数相同。假设是这种情况,问题是您在每次循环迭代中创建一个空列表并向其附加一个元素。在下一次迭代中,您将重新创建一个空列表,再次添加一个元素。
相反,您需要在循环外创建 fixedList
:
fixedList = []
for n in countList:
fixedList.append(float(n))
所以我有这个:
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)
但它仍然给我形状错误。我做错了什么?
当然需要保证countList
和xarray
的元素个数相同。假设是这种情况,问题是您在每次循环迭代中创建一个空列表并向其附加一个元素。在下一次迭代中,您将重新创建一个空列表,再次添加一个元素。
相反,您需要在循环外创建 fixedList
:
fixedList = []
for n in countList:
fixedList.append(float(n))