当前位置:网站首页>Drawing axes with dates using Matplotlib
Drawing axes with dates using Matplotlib
2022-06-24 04:59:00 【iam002】
Use matplotlib Draw axis with date
Source code and reference links
design sketch
Code
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
fig, ax = plt.subplots()
""" Generate the data """
beginDate = '2012-01-01'
endDate = '2018-01-01'
# Converts a date string to a number ( from 1970-01-01 The difference in the number of days counted )
x = np.arange(mdates.datestr2num(beginDate), mdates.datestr2num(endDate), 15)
y = np.random.randn(len(x))*3+2
data = {}
# The digital ( The days are different ) Convert to date object 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']) # Equivalent to the previous line
""" Format the axis """
# Set major scale , Every time 6 One scale per month
fmt_half_year = mdates.MonthLocator(interval=6)
ax.xaxis.set_major_locator(fmt_half_year)
# Set the secondary scale , One scale per month
fmt_month = mdates.MonthLocator() # The default can be
ax.xaxis.set_minor_locator(fmt_month)
# Set up x The scale format of the coordinate axis
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
# Set the range of the abscissa axis
datemin = np.datetime64(data['date'][0], 'Y')
datemax = np.datetime64(data['date'][-1], 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim(datemin, datemax)
# Set the display format of the scale
ax.format_xdata = mdates.DateFormatter('%Y-%m')
ax.format_ydata = lambda x : f'$x:.2f$'
ax.grid(True)
""" Automatically adjust the scale string """
# Automatic adjustment x The scale string of the axis ( rotate ) Make each string have enough space without overlapping
fig.autofmt_xdate()
plt.show()The classes used in the code are briefly introduced , You can click to view the specific parameters or usage .
- matplotlib.dates.datestr2num() Convert date to days difference
- numpy.datetime64() The digital ( The days are different ) Convert to date object
numpy.datetime64 - matplotlib.dates.MonthLocator() Set the date scale interval
- matplotlib.dates.DateFormatter() Set the date display format
- fig.autofmt_xdate() Automatic axis adjustment , Uncalled strings will overlap
边栏推荐
- Naming of tables in MySQL
- Getattribute return value is null
- How to use and apply for ECS? What parameters can be configured
- 解析后人类时代类人机器人的优越性
- What are the advantages of ECS? Is ECS better than VM?
- How to build an ECS and how to control the server through the local host
- 5g and industrial Internet
- What if the ECS forgets its password? How can I retrieve my forgotten password?
- SAP MTS/ATO/MTO/ETO专题之八:ATO模式2 D+空模式策略用85
- Bi-sql basic cognition
猜你喜欢

Leetcode (question 2) - adding two numbers

解析90后创客教育的主观积极性

梯度下降法介紹-黑馬程序員機器學習講義

Idea creates a servlet and accesses the 404 message

MySQL - SQL execution process

Facebook内部通告:将重新整合即时通讯功能

少儿编程教育在特定场景中的普及作用

阿里云新一代云计算体系架构 CIPU 到底是啥?

线性回归的损失和优化,机器学习预测房价

Analyzing the superiority of humanoid robot in the post human era
随机推荐
Ext4 file system jam caused by MEM CGroup OOM
Pg-pool-ii read / write separation experience
After purchasing Tencent ECs, how to solve packet loss in Internet access?
Recognize workplus again, not only im but also enterprise mobile application management expert
Critical service failed
Let children learn the application essence of steam Education
Getattribute return value is null
少儿编程课程改革后的培养方式
Leetcode (question 1) - sum of two numbers
Library management backstage
Integration of Alibaba cloud SMS services and reasons for illegal message signing
The principle of defer keyword in go
There are many ways to confirm and modify the remote port number
Redis pipeline technology speed and efficiency increased by 5 times
RedHat 8 time synchronization and time zone modification
Powerbi - for you who are learning
Idea creates a servlet and accesses the 404 message
Zhang Xiaodan, chief architect of Alibaba cloud hybrid cloud: evolution and development of government enterprise hybrid cloud technology architecture
Abnova peptide design and synthesis solutions
Chemical properties and specificity of Worthington Papain