Skip to content

Instantly share code, notes, and snippets.

@celeron55
Created September 26, 2023 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celeron55/fd4bb3942195c94250e277db8449d808 to your computer and use it in GitHub Desktop.
Save celeron55/fd4bb3942195c94250e277db8449d808 to your computer and use it in GitHub Desktop.
import calendar
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.patches import Rectangle
from matplotlib.ticker import FixedLocator
def create_month_calendar(year, month, ax):
month_days = calendar.monthrange(year, month)[1]
month_name = calendar.month_name[month]
ax.set_xlim([0, 7])
ax.set_ylim([0, 8]) # We add two extra rows: one for the month name and one for day labels.
ax.invert_yaxis()
ax.set_xticks([0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5])
ax.xaxis.set_major_locator(FixedLocator([0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5]))
ax.xaxis.set_major_formatter(plt.FixedFormatter(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]))
ax.yaxis.set_major_locator(plt.MaxNLocator(8))
ax.yaxis.set_major_formatter(plt.NullFormatter())
for spine in ax.spines.values():
spine.set_visible(False)
ax.tick_params(axis="x", which="both", length=0)
ax.tick_params(axis="y", which="both", length=0)
ax.get_yaxis().set_ticklabels([])
weekday_first_day = calendar.monthrange(year, month)[0]
day = 1
ax.text(3.5, 0.5, f"{month_name} {year}", ha='center', va='center', fontsize=14, fontweight='bold')
for row in range(2, 8):
for col in range(7):
# Add grid cell
rect = Rectangle((col, row), 1, 1, linewidth=1, edgecolor='0.5', facecolor='none')
ax.add_patch(rect)
if (row == 2 and col < weekday_first_day) or day > month_days:
ax.text(col + 0.5, row + 0.5, "", ha='center', va='center', fontsize=12)
else:
ax.text(col + 0.5, row + 0.5, str(day), ha='center', va='center', fontsize=12)
day += 1
def main():
# A4 dimensions, considering a slight reduction for print margins
fig = plt.figure(figsize=(8.27, 11.69)) # Width and Height in inches
# Using gridspec to place the month plots in 4 rows and 2 columns.
gs = gridspec.GridSpec(4, 2, figure=fig)
months_2023 = range(9, 13)
months_2024 = range(1, 5)
idx = 0
for month in months_2023:
ax = fig.add_subplot(gs[idx // 2, idx % 2])
create_month_calendar(2023, month, ax)
idx += 1
for month in months_2024:
ax = fig.add_subplot(gs[idx // 2, idx % 2])
create_month_calendar(2024, month, ax)
idx += 1
plt.tight_layout()
plt.savefig("calendar_sept2023_april2024.pdf")
plt.show()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment