gpt4 book ai didi

python - 随时间绘制总和

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:27 24 4
gpt4 key购买 nike

"Plotting a cumulative graph of python datetimes"提供了很好的方法来使用 matplotlib 将日期时间列表(见下文)绘制为随时间的累积计数:

[
datetime.datetime(2015, 12, 22),
datetime.datetime(2015, 12, 23),
datetime.datetime(2015, 12, 23), # note duplicate entry (graph increases by 2)
datetime.datetime(2015, 12, 24),
datetime.datetime(2015, 12, 25),
...
]

但是,我有一个新数据集,其中每个条目都有一个关联值(见下文)。我如何将其绘制为累积?还是我只需要迭代数据并将其累积到 x,y 绘图对中?

[
(datetime.datetime(2015, 12, 22), 6), # graph increases by 6
(datetime.datetime(2015, 12, 23), 5),
(datetime.datetime(2015, 12, 23), 4), # graph increases by 9
(datetime.datetime(2015, 12, 24), 12),
(datetime.datetime(2015, 12, 25), 14),
]

最佳答案

您需要做的就是拆分xy 轴,然后使用np.cumsum 累积y 值。或 np.add.accumulate .这是一个例子:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
import numpy as np

r = [(datetime.datetime(2015, 12, 22), 6), (datetime.datetime(2015, 12, 23), 5), (datetime.datetime(2015, 12, 23), 4), (datetime.datetime(2015, 12, 24), 12), (datetime.datetime(2015, 12, 25), 14)]

x, v = zip(*[(d[0], d[1]) for d in r]) # same as #x , v = [d[0] for d in r], [d[1] for d in r]
v = np.array(v).cumsum() # cumulative sum of y values

# now plot the results
fig, ax = plt.subplots(1)
ax.plot(x, v, '-o')
fig.autofmt_xdate()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
ax.xaxis.set_major_locator(mdates.DayLocator())
plt.show()

Result as plotted by matplotlib

关于python - 随时间绘制总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37529263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com