具有forin循环的列表的n个元素之和

2024-03-28 12:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个以天数为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,)

Tags: and代码inforlenhave图表range
1条回答
网友
1楼 · 发布于 2024-03-28 12:28:27

我可能没有正确地理解你想要达到的目标,但是只要读一句话“创建一个以天数为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

相关问题 更多 >