欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Python Matplotlib.dates.DateFormatter 示例解释

最编程 2024-05-08 11:00:32
...

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

Matplotlib.dates.DateFormatter

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

用法: class matplotlib.dates.DateFormatter(fmt, tz=None)

参数:

  1. fmt:它接受strftime格式字符串进行格式化,并且是必需的参数。
  2. tz:它保存有关时区的信息。如果设置为none,则在格式化日期字符串时将忽略时区信息。

范例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()

输出: