使用imshow在matplotlib绘图中设置x轴日期
我刚开始学习用matplotlib编程。我用imshow()和一个数组创建了一个颜色图。最开始,坐标轴只是我数组的行号和列号。我使用了extent = (xmin,xmax,ymin,ymax)来把x轴设置成Unix时间和高度。
现在我想把x轴从Unix时间(982376726, 982377321)改成协调世界时(UT)(02:25:26, 02:35:21)。我已经创建了一个包含HH:MM:SS格式的时间范围的列表。但我不太确定怎么把现在的x轴替换成这些新数字,而不改变颜色图(或者让它消失)。
我看过datetime.time,但搞得我有点困惑。
任何帮助都非常感谢!
1 个回答
40
我写了一些示例代码,希望能帮助你解决问题。
这段代码首先使用 numpy.random
生成一些随机数据。接着,它会根据你问题中给出的两个 Unix 时间戳来计算 x 轴的范围,而 y 轴的范围则是一些普通的数字。
然后,代码会把这些随机数据绘制出来,并使用 pyplot
的方法把 x 轴的格式转换成更好看的字符串(而不是 Unix 时间戳或数组数字)。
代码中有很多注释,应该能解释你需要的所有内容。如果还有不明白的地方,请留言问我。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
# Generate some random data for imshow
N = 10
arr = np.random.random((N, N))
# Create your x-limits. Using two of your unix timestamps you first
# create a list of datetime.datetime objects using map.
x_lims = list(map(dt.datetime.fromtimestamp, [982376726, 982377321]))
# You can then convert these datetime.datetime objects to the correct
# format for matplotlib to work with.
x_lims = mdates.date2num(x_lims)
# Set some generic y-limits.
y_lims = [0, 100]
fig, ax = plt.subplots()
# Using ax.imshow we set two keyword arguments. The first is extent.
# We give extent the values from x_lims and y_lims above.
# We also set the aspect to "auto" which should set the plot up nicely.
ax.imshow(arr, extent = [x_lims[0], x_lims[1], y_lims[0], y_lims[1]],
aspect='auto')
# We tell Matplotlib that the x-axis is filled with datetime data,
# this converts it from a float (which is the output of date2num)
# into a nice datetime string.
ax.xaxis_date()
# We can use a DateFormatter to choose how this datetime string will look.
# I have chosen HH:MM:SS though you could add DD/MM/YY if you had data
# over different days.
date_format = mdates.DateFormatter('%H:%M:%S')
ax.xaxis.set_major_formatter(date_format)
# This simply sets the x-axis data to diagonal so it fits better.
fig.autofmt_xdate()
plt.show()