使用 matplotlib 绘制带日期的坐标轴

使用 matplotlib 绘制带日期的坐标轴

源码及参考链接

效果图

在这里插入图片描述

代码

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots()

"""生成数据"""
beginDate = '2012-01-01'
endDate = '2018-01-01'

# 将日期字符串转化为数字(从1970-01-01算起的天数差)
x = np.arange(mdates.datestr2num(beginDate), mdates.datestr2num(endDate), 15)
y = np.random.randn(len(x))*3+2

data = {}
# 将数字(天数差)转为日期对象 numpy.datetime64
data['date'] = [np.datetime64(int(c), 'D') for c in x]
data['value'] = y
ax.plot('date', 'value', data=data) 
# ax.plot(data['date'], data['value']) # 与前一行是等效的


"""设置坐标轴的格式"""
# 设置主刻度, 每6个月一个刻度
fmt_half_year = mdates.MonthLocator(interval=6)
ax.xaxis.set_major_locator(fmt_half_year)

# 设置次刻度,每个月一个刻度
fmt_month = mdates.MonthLocator() # 默认即可
ax.xaxis.set_minor_locator(fmt_month)

# 设置 x 坐标轴的刻度格式
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))

# 设置横坐标轴的范围
datemin = np.datetime64(data['date'][0], 'Y')
datemax = np.datetime64(data['date'][-1], 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim(datemin, datemax)

# 设置刻度的显示格式
ax.format_xdata = mdates.DateFormatter('%Y-%m')
ax.format_ydata = lambda x : f'$x:.2f$'
ax.grid(True)

"""自动调整刻度字符串"""
# 自动调整 x 轴的刻度字符串(旋转)使得每个字符串有足够的空间而不重叠
fig.autofmt_xdate() 

plt.show()

代码中使用到的类简单介绍一下,具体参数或用法可以点击查看。

未调整字符串

未调整字符串的运行结果

  • 4
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wreng我是002

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值