Reputation: 17002
"Plotting a cumulative graph of python datetimes" provides great methods to use matplotlib to plot a list of datetimes (see below) as a cumulative count over time:
[
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),
...
]
However, I have a new dataset where each entry has an associated value (see below). How can I plot this as an accumulation? Or do I just need to iterate over the data and accumulate it into x,y plotting pairs myself?
[
(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),
]
Upvotes: 2
Views: 4977
Reputation: 69222
All you need to do is split the x
and y
axes, and then accumulate the y-values using either np.cumsum
or np.add.accumulate
. Here's an example:
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()
Upvotes: 5