matplotlob绘制日历图4-6月份加上农历
时间: 2024-02-20 07:56:27 浏览: 166
要绘制日历图并加上农历,可以使用Python的calendar和lunarcalendar库。calendar库可以生成日历,lunarcalendar库可以生成农历。然后使用Matplotlib绘制图形。以下是一个示例代码,可以绘制4-6月份的日历图,并在每个日期下方显示农历。
```python
import calendar
import lunarcalendar
import matplotlib.pyplot as plt
# 设置起始月份和结束月份
start_month = 4
end_month = 6
# 获取每个月的日历和农历
calendars = []
lunar_calendars = []
for month in range(start_month, end_month + 1):
# 获取日历
cal = calendar.monthcalendar(2021, month)
calendars.append(cal)
# 获取农历
lunar_cal = []
for week in cal:
lunar_week = []
for day in week:
if day == 0:
lunar_week.append('')
else:
lunar = lunarcalendar.LunarDate.fromSolarDate(2021, month, day)
lunar_week.append(str(lunar))
lunar_cal.append(lunar_week)
lunar_calendars.append(lunar_cal)
# 绘制图形
fig, axs = plt.subplots(nrows=len(calendars), ncols=7, figsize=(12, 8))
for i, cal in enumerate(calendars):
for j, week in enumerate(cal):
for k, day in enumerate(week):
if day == 0:
axs[i, k].axis('off')
else:
axs[i, k].text(0.5, 0.5, str(day), ha='center', va='center')
axs[i, k].text(0.5, 0.2, lunar_calendars[i][j][k], ha='center', va='center', fontsize=8)
axs[i, k].axis('off')
for k in range(7 - len(cal[-1])):
axs[i, -1-k].axis('off')
axs[i, 0].set_ylabel(calendar.month_name[start_month+i], fontsize=12)
plt.tight_layout()
plt.show()
```
运行上面的代码,就可以绘制出4-6月份的日历图,并在每个日期下方显示农历。
阅读全文