gpt4 book ai didi

python - 从 HH :MM:SS to HH:SS 重新格式化 matplotlib x 轴

转载 作者:行者123 更新时间:2023-11-30 23:24:03 27 4
gpt4 key购买 nike

我有一天中每一分钟的数据点:

import numpy as np
data = np.random.random(1440,)

# I can represent minutes as integers:

mins = np.arange(1440,dtype=np.int)

# convert to datetime

import datetime
times=np.array([datetime.datetime(2014, 5, 13, int(p/60), p%60) for p in mins])

# and plot for every 20 samples:

import matplotlib.pyplot as plt
plt.plot(times[1::20], data[1::20])

给我:

enter image description here

如何将 x 轴格式更改为 HH:MM?

我尝试使用 datetime.time() 函数而不是 datetime.datetime(),但这会导致错误。

最佳答案

您可以使用 custom tick formatter来自dates package按照您的意愿呈现日期。

扩展您的代码示例:

import numpy as np
import datetime
import matplotlib.pyplot as plt
from matplotlib import dates

data = np.random.random(1440,)
# I can represent minutes as integers:
mins = np.arange(1440,dtype=np.int)
# convert to datetime
times=np.array([datetime.datetime(2014, 5, 13, int(p/60), p%60) for p in mins])
# and plot for every 20 samples:
plt.plot(times[1::20], data[1::20])

# generate a formatter, using the fields required
fmtr = dates.DateFormatter("%H:%M")
# need a handle to the current axes to manipulate it
ax = plt.gca()
# set this formatter to the axis
ax.xaxis.set_major_formatter(fmtr)

plt.show()

格式字符串是根据 strftime docs 定义的.

example custom date formatting

关于python - 从 HH :MM:SS to HH:SS 重新格式化 matplotlib x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23636666/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com