x 轴上的 Matplotlib 日期时间
Matplotlib datetime on the x axis
如果您的 x 轴上有日期时间对象,您如何在 matplotlib 的点击事件处理程序中获取点击的对象?
即当你这样做时:
def onclick2(event):
print event.x
onClickId = figure.canvas.mpl_connect('button_press_event', OnClick2)
我试过 event.x、event.xdata 和 event._x,它们都是 return 整数
它们可能真的是整数...我相信 matplotlib 通过先将日期转换为整数或浮点数来绘制日期。使用您的事件数据尝试 matplotlib dates 模块中的 num2date
函数,这可能会产生您想要的结果。
我在尝试从使用 matplotlib 绘制的 pandas 时间索引数据帧中 return 时间戳 x 轴数据时遇到了类似的问题。尝试 Ajean 在 event.xdata return 上的 num2date 建议是一个太大而不能作为日期数字的浮点值(例如 2014-4-14 2:25 的 23286385.16)。
要扩展 Ajean 的建议,最好先使用 matplotlib.dates.date2num
函数将 datetime 对象转换为 numpy.float64。然后,您可以将创建的 numpy.float64 数组用作带有 matplotlib 事件处理程序的 x 轴。从事件处理程序返回的 event.xdata 然后可以使用 matplotlib.dates.num2date
函数转换回日期时间。
您应该使用 num2date(…)
to get the date back. See 作为如何使用它的示例。
如果您的 x 轴上有日期时间对象,您如何在 matplotlib 的点击事件处理程序中获取点击的对象?
即当你这样做时:
def onclick2(event):
print event.x
onClickId = figure.canvas.mpl_connect('button_press_event', OnClick2)
我试过 event.x、event.xdata 和 event._x,它们都是 return 整数
它们可能真的是整数...我相信 matplotlib 通过先将日期转换为整数或浮点数来绘制日期。使用您的事件数据尝试 matplotlib dates 模块中的 num2date
函数,这可能会产生您想要的结果。
我在尝试从使用 matplotlib 绘制的 pandas 时间索引数据帧中 return 时间戳 x 轴数据时遇到了类似的问题。尝试 Ajean 在 event.xdata return 上的 num2date 建议是一个太大而不能作为日期数字的浮点值(例如 2014-4-14 2:25 的 23286385.16)。
要扩展 Ajean 的建议,最好先使用 matplotlib.dates.date2num
函数将 datetime 对象转换为 numpy.float64。然后,您可以将创建的 numpy.float64 数组用作带有 matplotlib 事件处理程序的 x 轴。从事件处理程序返回的 event.xdata 然后可以使用 matplotlib.dates.num2date
函数转换回日期时间。
您应该使用 num2date(…)
to get the date back. See