3

I have a sorted list of datetime objects as follows:

X = [datetime.date(2017, 1, 14), datetime.date(2017, 1, 14), datetime.date(2017, 1, 16), datetime.date(2017, 1, 16), datetime.date(2017, 1, 18), datetime.date(2017, 1, 22), datetime.date(2017, 1, 24), datetime.date(2017, 1, 24), datetime.date(2017, 1, 29), datetime.date(2017, 2, 4), datetime.date(2017, 2, 10), datetime.date(2017, 2, 22), datetime.date(2017, 2, 28), datetime.date(2017, 3, 8), datetime.date(2017, 3, 28), datetime.date(2017, 4, 17), datetime.date(2017, 4, 20), datetime.date(2017, 4, 20), datetime.date(2017, 5, 16), datetime.date(2017, 5, 26), datetime.date(2017, 6, 12), datetime.date(2017, 6, 23), datetime.date(2017, 6, 28), datetime.date(2017, 7, 28), datetime.date(2017, 8, 14), datetime.date(2017, 8, 29), datetime.date(2017, 8, 29), datetime.date(2017, 9, 26), datetime.date(2017, 10, 4), datetime.date(2017, 10, 5), datetime.date(2017, 10, 8), datetime.date(2017, 11, 20), datetime.date(2017, 12, 2), datetime.date(2017, 12, 11), datetime.date(2017, 12, 11), datetime.date(2018, 2, 14), datetime.date(2018, 2, 16), datetime.date(2018, 3, 2), datetime.date(2018, 3, 5), datetime.date(2018, 3, 28)]

The goal is to plot a line chart with X-axis as date, and Y-axis as the no. of times each of the dates appears in the list. I understand that the lamest way to get the line chart is to remove duplicates from X, and generate another list Y which contains the frequency of each datetime object in X, and do a

plt.plot(X,Y)

But is there a smarter / more pythonic way of doing this?

I've already read Plotting time in Python with Matplotlib, but that doesn't help.

Prateek Dewan
  • 1,587
  • 3
  • 16
  • 29
  • What's not smart/pythonic about cleaning your data to display it as you want? Even if there was an option, `matplotlib` would be doing the same thing. – zwer Apr 09 '18 at 11:27
  • I was hoping matplotlib (or some other library) would have a function to convert a list Z to the X, Y form where X is the unique elements in Z, and Y is the frequencies. The closest I can think of is Counter, but the dictionary returned by Counter wouldn't return X as sorted. Basically, this is an operation I've done hundreds of times in the past. I wonder if there's a function for it. – Prateek Dewan Apr 09 '18 at 11:35

1 Answers1

2

matplotlib in general does not provide ways to aggregate your data. It is a plotting library after all.

Instead you can rely on the in-built python options, or use other packages like numpy or pandas.

For example using numpy.unique:

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

Z = [datetime.date(2017, 1, 14), datetime.date(2017, 1, 14), ...,
    ..., datetime.date(2018, 3, 28)] # data from question

X,Y = np.unique(Z, return_counts=True)

plt.plot(X,Y)

plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712