随时间变化的总和

时间:2016-05-30 15:29:18

标签: python datetime matplotlib plot graph

"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),
]

1 个答案:

答案 0 :(得分:4)

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

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