带for-in循环的列表的n个元素的总和

时间:2019-01-30 22:17:41

标签: python matplotlib

我正在尝试创建一个以天数为x轴和总小时数为y轴的图形,但是我不知道如何创建y轴。代码是:

hours_per_day = [1, 4, 3, 2, 3, 1]
days = [x for x in range(len(hours_per_day))]


def total_hours():
        y = 0
        for x in hours_per_day:
                y = x + y
        return y


plt.plot(days, total_hours, label="Total Hours")

错误:

ValueError: x and y must have same first dimension, but have shapes (6,) and (1,)

1 个答案:

答案 0 :(得分:0)

我可能无法正确理解您要实现的目标,而只是阅读句子“创建一个以天数为x轴,总时数为y轴的图表”

import numpy as np
import matplotlib.pyplot as plt

hours_per_day = [1, 4, 3, 2, 3, 1]

plt.plot(np.cumsum(hours_per_day))

plt.show()

enter image description here