Skip to content

Instantly share code, notes, and snippets.

@h4k1m0u
Last active November 1, 2025 12:41
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 argparse
from pathlib import Path
from datetime import datetime
import calendar
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
# import matplotlib.dates as mdates
# current date
year_current = datetime.now().year
month_current = datetime.now().month
# read command-line arguments
description = 'Plot bar chart of dates appearing in the txt file using matplotlib'
help_path_dates = 'txt file with dates in yyyy-mm-dd format'
help_month = f'must be in [1, 12], and defaults to current month ({month_current})'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('path_dates', help=help_path_dates)
parser.add_argument('month', type=int, choices=range(1, 13), nargs='?', default=month_current, metavar='month', help=help_month)
args = parser.parse_args()
path_dates = args.path_dates
month = args.month
month_name = calendar.month_name[month]
if not Path(path_dates).is_file():
print(f"Error: File {path_dates} doesn't exist")
exit(0)
# x-coords: dates
date_min = np.datetime64(f'{year_current}-{month:02}')
date_max = np.datetime64(f'{year_current}-{month + 1:02}')
days = np.arange(date_min, date_max, dtype='datetime64[D]')
# y-coords: yes/no
days_yes = np.loadtxt(path_dates, dtype='datetime64[D]')
ys = []
for day in days:
y = 1 if day in days_yes else 0
ys.append(y)
# print avg. per week in given month
n_days_month = len(days)
N_DAYS_WEEK = 7
n_weeks_month = n_days_month / N_DAYS_WEEK
n_ones = np.count_nonzero(ys)
avg_week = n_ones / n_weeks_month
print(f'Average per week for {month_name} {year_current}: {avg_week:.2f}')
# plot ys as a function of dates
ax = plt.gca()
ax.set_title(f'{month_name} {year_current}')
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