将 x 轴上的秒转换为 min:sec,同时保持相同的 x 限制

Y.Y*_*not 2 python time numpy matplotlib

我正在绘制随时间变化的值,以秒为单位。但是,我想在 x 轴上显示以分钟为单位的时间:秒。我现在已经这样做了,但我得到了像 0.8 这样的小数,这是你在时间表示法中不想要的。我尝试用 修复它'{}:{}.format(mins, secs)',但随后我的 x 值变成字符串,并且我无法再获得适当的 x lims。

有谁知道一种将秒转换为分钟:秒的好方法,同时能够保持相同的 xlims?

import matplotlib.pyplot as plt


y = np.random.rand(90, 1)

print(y)
    
x = np.arange(1380, 1470, 1)    # seconds
x = x/60                        # minutes


plt.plot(x, y)
plt.xlabel('Time (mins)')
Run Code Online (Sandbox Code Playgroud)

例子

小智 5

如果这对你来说不是问题,我通常使用 pandas 转换为日期时间

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

y = np.random.rand(90, 1)
x = np.arange(1380, 1470, 1)    # seconds
x = x/60                        # minutes
t = pd.to_datetime(x, unit='m') # convert to datetime

fig = plt.figure()
plt.plot(t, y)
plt.xlabel('Time (mins)')
fig.autofmt_xdate() # auto format
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述