更改 Matplotlib 中的 X 轴日期时间间隔以仅显示分钟,按从第一个条目到最后一个条目的顺序

问题描述 投票:0回答:1

我有以下代码(实际上模仿了我在真实项目中的代码 - 数据来自其他来源):

from datetime import datetime, timedelta
import random
import matplotlib.pyplot as plt

# Define the starting datetime
start_datetime = datetime(2024, 1, 1)

# Create a dictionary with 100 entries
sample_dictionary = {}
for i in range(100):
    # Generate the datetime key
    key = start_datetime.strftime("%Y%m%d%H%M%S%f")[:-3]  # Remove the microseconds

    # Add the entry to the dictionary
    random_integer = random.randint(30, 500)
    sample_dictionary[key] = random_integer

    # Increment the datetime for the next entry
    random_step_seconds = random.randint(5, 120)
    start_datetime += timedelta(seconds=random_step_seconds)

# Print the sample dictionary
# Convert datetime strings to datetime objects
datetime_objects = [datetime.strptime(key, "%Y%m%d%H%M%S%f") for key in sample_dictionary.keys()]
integer_values = list(sample_dictionary.values())

fg, axs = plt.subplots()
axs.set_xlabel('Dictation DT')
axs.set_ylabel('TAT in minutes')
axs.set_title('TAT over the last x hours')

axs.plot(datetime_objects, integer_values, marker='o')

plt.tight_layout()
plt.show()

显示为:

我想在 X 轴上仅显示时间部分,hh:mm。我怎么做?我还想控制在 X 轴 (hh:mm) 上显示刻度的频率,因为如果图表有更多点,我实际上不需要显示每个相应的 X 时间。

python matplotlib datetime
1个回答
0
投票

您可以使用 matplotlib.dates 来实现这一点。只需使用 mdates.MinuteLocator() 和所需的

interval
值调用
matplotlib.axis.Axis.set_major_locator
即可。 x 轴的“hh:mm”格式可以使用 matplotlib.axis.Axis.set_major_formatter
mdates.DateFormatter("%H:%M")
设置,如下所示:


# your code

import matplotlib.dates as mdates

# your code

# labelled ticks every 20 minutes
axs.xaxis.set_major_locator(mdates.MinuteLocator(interval=20))
axs.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))

# your code

输出:

© www.soinside.com 2019 - 2024. All rights reserved.