📜  Python中的 Matplotlib.dates.AutoDateFormatter 类

📅  最后修改于: 2022-05-13 01:54:32.268000             🧑  作者: Mango

Python中的 Matplotlib.dates.AutoDateFormatter 类

Matplotlib是Python中用于数组二维图的惊人可视化库。 Matplotlib 是一个基于 NumPy 数组构建的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈配合使用。

matplotlib.dates.AutoDateFormatter

matplotlib.dates.AutoDateFormatter 类用于找出用于日期的最佳格式。这最好与 AutoDateLocator 一起使用。它有一个映射刻度刻度的字典和一个格式字符串。默认情况下,它如下所示:

该字典中大于或等于当前比例的键由该算法挑选并用于格式化字符串。这个字典也可以像下面这样定制:

locator = AutoDateLocator()
formatter = AutoDateFormatter(locator)

# only show hour and minute
formatter.scaled[1/(24.*60.)] = '%H:%M'

如果 self.scaled 中没有值大于 locator._get_unit() 返回的单位,则使用默认格式。

示例 1:

Python3
import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateLocator, AutoDateFormatter, date2num
 
# make my own data:
date = '2020-02-23'
low = 10
 
# how to format dates:
date_datetime = datetime.datetime.strptime(date, '% Y-% m-% d')
int_date = date2num( date_datetime)
 
# create plots:
figure, axes = plt.subplots()
 
# plot data:
axes.bar(int_date, low, label ="", color ="green")
 
# format date
locator = AutoDateLocator()
axes.xaxis.set_major_locator(locator)
axes.xaxis.set_major_formatter( AutoDateFormatter(locator) )
 
# apply autoformatter for displaying of dates
min_date = date2num( datetime.datetime.strptime('2020-02-16', '% Y-% m-% d') )
max_date = date2num( datetime.datetime.strptime('2020-02-28', '% Y-% m-% d') )
axes.set_xlim([min_date, max_date])
figure.autofmt_xdate()
 
# show plot:
plt.show()


Python3
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
 
# generate some random data for
# approx 5 yrs
random_data = [float(random.randint(1487517521,
                                    14213254713))
               for _ in range(1000)]
 
# convert the epoch format to
# matplotlib date format
mpl_data = mdates.epoch2num(random_data)
 
# plotting the graph
fig, axes = plt.subplots(1, 1)
axes.hist(mpl_data, bins = 51, color ='green')
 
locator = mdates.AutoDateLocator()
 
axes.xaxis.set_major_locator(locator)
axes.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))
 
plt.show()


输出:

示例 2:

Python3

import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
 
# generate some random data for
# approx 5 yrs
random_data = [float(random.randint(1487517521,
                                    14213254713))
               for _ in range(1000)]
 
# convert the epoch format to
# matplotlib date format
mpl_data = mdates.epoch2num(random_data)
 
# plotting the graph
fig, axes = plt.subplots(1, 1)
axes.hist(mpl_data, bins = 51, color ='green')
 
locator = mdates.AutoDateLocator()
 
axes.xaxis.set_major_locator(locator)
axes.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))
 
plt.show()

输出: