导入模块
import datetime
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
设置格式并导入数据
months = mdates.MonthLocator()#刻度上显示出月份
days = mdates.DayLocator()#刻度上显示出每月的几号
timeFmt = mdates.DateFormatter('%Y-%m')#格式化时间形式(年-月)
#input data
events = [datetime.date(2021,1,23),datetime.date(2021,1,28),
datetime.date(2021,2,3),datetime.date(2021,2,21),
datetime.date(2021,3,15),datetime.date(2021,3,24),
datetime.date(2021,4,8),datetime.date(2021,4,24)]
readings = [12,22,25,20,18,15,17,14]
绘图,设置刻度
'''
fig代表绘图窗口(Figure);ax代表这个绘图窗口上的坐标系(axis)
fig,ax = plt.subplots()等价于:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plt.plot(events,readings)
'''
fig,ax = plt.subplots()
#设置主副刻度
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(timeFmt)
ax.xaxis.set_minor_locator(days)
#字符串旋转
for label in ax.get_xticklabels():
label.set_rotation(30) #逆时针旋转30°
label.set_horizontalalignment('right') #右对齐
plt.show()
结果
参考:
法比奥·内利. Python数据分析实战:第2版.北京:人民邮电出版社, 2019.11.
fig, ax = plt.subplots(figsize = (a, b))解析 与 plt.subplot()函数解析_哎呦-_-不错的博客-CSDN博客