【问题标题】:Dates in the xaxis for a matplotlib plot with imshow带有 imshow 的 matplotlib 图的 x 轴上的日期
【发布时间】:2014-06-02 02:32:22
【问题描述】:

所以我是使用 matplotlib 编程的新手。我使用 imshow() 和一个数组创建了一个颜色图。起初,轴只是我的数组的行号和列号。我使用 extent = (xmin,xmax,ymin,ymax) 分别获取 unix 时间和高度的 x 轴。

我想将 x 轴从 unix 时间 (982376726,982377321) 更改为 UT(02:25:26, 02:35:21)。我在 HH:MM:SS 中创建了一个时间范围列表。我不确定如何在不更改颜色图(或使其消失)的情况下用这些新数字替换我当前的 x 轴。

我正在查看 datetime.time 但我对它感到困惑。

任何帮助将不胜感激!

【问题讨论】:

  • 你能提供你目前拥有的代码吗?

标签: python datetime matplotlib plot imshow


【解决方案1】:

我整理了一些示例代码,可以帮助您解决问题。

代码首先使用numpy.random 生成一些随机数据。然后它会计算您的 x 限制和 y 限制,其中 x 限制将基于您问题中给出的两个 unix 时间戳,而 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()

【讨论】:

  • 这很有帮助!!只是为了澄清一下,为了能够使用情节和轴,我应该总是做一些子情节吗?
  • 不一定。您可以使用更简单的plt.plot,但我认为您必须使用plt.xaxis_date()。您可能还必须执行gca().xaxis.set_major_formatter(...),其中gca 函数仅返回当前轴对象(相当于仅以 fig, ax 开头)。
  • 有没有办法让 Matplotlib 自动选择标签中的时间分辨率?它通常会这样做(例如,在 x 轴上使用带有日期的plot() 时),但是如果我在您的示例中省略了DateFormatter 中的格式说明符,我只会得到年份(例如,[2015, 2015, 2015 , ...])。
  • 没关系;我刚刚找到AutoDateLocatorAutoDateFormatter
猜你喜欢
  • 2018-04-13
  • 2020-06-09
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 2020-07-08
  • 2015-05-02
  • 2019-03-11
  • 2017-07-01
相关资源
最近更新 更多