Python中的 Matplotlib.dates.datestr2num()
Matplotlib是Python中用于数组二维图的惊人可视化库。 Matplotlib 是一个基于 NumPy 数组构建的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈配合使用。
matplotlib.dates.datestr2num()
matplotlib.dates.datestr2num()
函数用于通过使用dateutil.parser.parser()
将日期字符串转换为 datenum。
Syntax: matplotlib.dates.datestr2num(d, default=None)
Parameters:
- d: It is a string or a sequence of strings representing the dates.
- default: This is an optional parameter that is a datetime instance. This is used when fields are not present in d, as a default.
示例 1:
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import (
DateFormatter, AutoDateLocator, AutoDateFormatter, datestr2num
)
days = [
'30/01/2019',
'31/01/2019',
'01/02/2019',
'02/02/2019',
'03/02/2019',
'04/02/2019'
]
data1 = [2, 5, 13, 6, 11, 7]
data2 = [6, 3, 10, 3, 6, 5]
z = datestr2num([
datetime.strptime(day, '%d/%m/%Y').strftime('%m/%d/%Y')
for day in days
])
r = 0.25
figure = plt.figure(figsize =(8, 4))
axes = figure.add_subplot(111)
axes.bar(z - r, data1, width = 2 * r,
color ='g', align ='center',
tick_label = day)
axes.bar(z + r, data2, width = 2 * r,
color ='y', align ='center',
tick_label = day)
axes.xaxis_date()
axes.xaxis.set_major_locator(
AutoDateLocator(minticks = 3, interval_multiples = False))
axes.xaxis.set_major_formatter(DateFormatter("%d/%m/%y"))
plt.show()
输出:
示例 2:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates
dates = ['1920-05-06',
'1920-05-07',
'1947-05-08',
'1920-05-09']
converted_dates = matplotlib.dates.datestr2num(dates)
x_axis = (converted_dates)
y_axis = range(0, 4)
plt.plot_date( x_axis, y_axis, '-' )
plt.show()
输出: