Skip to content

Instantly share code, notes, and snippets.

@h4k1m0u
Last active July 5, 2025 15:42
Show Gist options
  • Save h4k1m0u/faa2efd32ee4dc0c91198d44baadb7fc to your computer and use it in GitHub Desktop.
Save h4k1m0u/faa2efd32ee4dc0c91198d44baadb7fc to your computer and use it in GitHub Desktop.
Plot bar chart of dates appearing in the txt file using matplotlib
01-05-2025
08-05-2025
29-05-2025
#!/usr/bin/env python3
"""
Python datetime: https://docs.python.org/3/library/datetime.html
Numpy datetime: https://numpy.org/doc/stable/reference/arrays.datetime.html
Pandas datetime: https://pandas.pydata.org/docs/user_guide/timeseries.html
"""
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
# import matplotlib.dates as mdates
# x-coords: dates (use tomorrow as upper bound to include today in range)
tomorrow = np.datetime64(datetime.today()) + np.timedelta64(1, 'D')
date_start = np.datetime64('2025-05-23')
days = np.arange(date_start, tomorrow, dtype='datetime64[D]')
# y-coords: yes/no
days_yes = np.loadtxt('dates.txt', dtype='datetime64[D]')
ys = []
for day in days:
y = 1 if day in days_yes else 0
ys.append(y)
# plot ys as a function of dates
ax = plt.gca()
ax.bar(days, ys, width=1.0, align='edge', linewidth=1, color='brown')
ax.set_xlabel('Weeks', fontsize='large', fontweight='bold', color='brown')
ax.set_ylabel('Yes/No', fontsize='large', fontweight='bold', color='brown')
# show minor ticks without a label & major ones with rotated labels on x-axis
# ax.xaxis.set_minor_locator(mdates.MonthLocator())
ax.xaxis.set_major_locator(MultipleLocator(7))
ax.xaxis.set_minor_locator(MultipleLocator(1))
ax.tick_params(axis='x', which='major', length=7, width=2)
# show ticks on y-axis
ax.set_yticks(np.arange(2), [ 'No', 'Yes' ])
ax.set_ylim(ymin=0, ymax=1)
# show guides
ax.grid(visible=True, axis='x', which='major')
ax.grid(visible=True, axis='x', which='minor', linewidth=0.5, linestyle=':')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment