📜  Python中的 Matplotlib.dates.ConciseDateFormatter 类

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

Python中的 Matplotlib.dates.ConciseDateFormatter 类

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

matplotlib.dates.ConciseDateFormatter

matplotlib.dates.ConciseDateFormatter类用于找出用于日期的最佳格式,并使其尽可能紧凑但完整。这更常与AutoDateLocator一起使用。

示例 1:

import numpy as np
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
  
   
# dummy date
dummy_date = np.arange("2020-04-10", 
                       "2020-05-14",
                       dtype ="datetime64")
  
random_x = np.random.rand(len(dummy_date))
   
figure, axes = plt.subplots()
  
axes.plot(dummy_date, random_x)
axes.xaxis.set(
    major_locator = mdates.AutoDateLocator(minticks = 1,
                                           maxticks = 5),
)
  
locator = mdates.AutoDateLocator(minticks = 15,
                                 maxticks = 20)
formatter = mdates.ConciseDateFormatter(locator)
  
axes.xaxis.set_major_locator(locator)
axes.xaxis.set_major_formatter(formatter)
   
plt.show()

输出:

示例 2:

import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
  
  
dummy_date = datetime.datetime(2020, 2, 1)
  
# random date generator
dates = np.array([dummy_date + datetime.timedelta(hours =(2 * i))
                  for i in range(732)])
date_length = len(dates)
  
np.random.seed(194567801)
y_axis = np.cumsum(np.random.randn(date_length))
  
lims = [(np.datetime64('2020-02'), 
         np.datetime64('2020-04')),
        (np.datetime64('2020-02-03'), 
         np.datetime64('2020-02-15')),
        (np.datetime64('2020-02-03 11:00'), 
         np.datetime64('2020-02-04 13:20'))]
  
figure, axes = plt.subplots(3, 1, 
                            constrained_layout = True, 
                            figsize =(6, 6))
  
for nn, ax in enumerate(axes):
      
    locator = mdates.AutoDateLocator(minticks = 3, maxticks = 7)
    formatter = mdates.ConciseDateFormatter(locator)
      
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
  
    ax.plot(dates, y_axis)
    ax.set_xlim(lims[nn])
      
axes[0].set_title('Concise Date Formatter')
  
plt.show()

输出: