📜  Python中的 Matplotlib.dates.DateFormatter 类

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

Python中的 Matplotlib.dates.DateFormatter 类

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

Matplotlib.dates.DateFormatter

matplotlib.dates.DateFormatter类用于使用 strftime 格式的字符串格式化刻度(自纪元以来的秒数)。它的基类是matplotlib.ticker.Formatter

示例 1:

import numpy
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas
  
   
total_bars = 25
numpy.random.seed(total_bars)
   
dates = pandas.date_range('3/4/2020', 
                          periods=total_bars,
                          freq='m')
  
diff = pandas.DataFrame(
    data=numpy.random.randn(total_bars), 
    index=dates,
    columns=['A']
)
   
figure, axes = plt.subplots(figsize=(10, 6))
  
axes.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
  
axes.bar(diff.index,
         diff['A'], 
         width=25, 
         align='center')

输出:

示例 2:

import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime
  
origin = ['2020-02-05 17:17:55',
          '2020-02-05 17:17:51', 
          '2020-02-05 17:17:49']
  
a = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in origin]
  
b = ['35.764299', '20.3008', '36.94704']
  
x = matplotlib.dates.date2num(a)
formatter = matplotlib.dates.DateFormatter('%H:%M:%S')
  
figure = plt.figure()
axes = figure.add_subplot(1, 1, 1)
  
axes.xaxis.set_major_formatter(formatter)
plt.setp(axes.get_xticklabels(), rotation = 15)
  
axes.plot(x, b)
plt.show()

输出: