所以我有这个:
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需要是float,所以我把代码更改为:
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)
但它仍然给我形状错误 . 我究竟做错了什么?
1 回答
当然,您需要确保
countList
和xarray
具有相同数量的元素 . 假设是这种情况,问题是您在每个循环迭代中创建一个空列表并向其追加单个元素 . 在下一次迭代中,您将重新创建一个空列表,再次添加一个元素 .相反,您需要在循环外创建
fixedList
: