【问题标题】:How to make hist2d xaxis ticks as datetime format?如何将 hist2d xaxis 标记为日期时间格式?
【发布时间】:2020-04-05 04:32:00
【问题描述】:

我想将 unixtime 转换为 datetime 格式以使用 hist2d 显示以下数据。 但是,每次我将 unixtime 转换为 datetime 时

我得到“TypeError: ufunc 'isfinite' not supported for the input types, and the input could not be safe to force to any supported types based on the cast rule ''safe''”

我要绘制的数据:

如果我将 unixtime 作为 xsticks,这就是我绘制的:

这是应该的情节

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

# example data
x = df_1['unix_time']
y = df_1['bid_ask_spread']

# Set up x_ticks
time_frame = np.linspace(1575254259187, 1575513459187, 73)
x_ticks = []
for i in time_frame:
    x_ticks.append(to_datetime(i))

# make a custom colormap with transparency
ncolors = 256
color_array = plt.get_cmap('YlOrRd')(range(ncolors))
color_array[:, -1] = np.linspace(0, 1, ncolors)
cmap = LinearSegmentedColormap.from_list(name='YlOrRd_alpha', colors=color_array)

fig, ax1 = plt.subplots(1, 1, figsize=(16,9), dpi=80)

ax1.hist2d(x, y, bins=[71, 81], cmap=cmap, edgecolor='white')

# ax1.set_xticks(x_ticks[::5])
ax1.set_ylim(bottom=0)

plt.show()

【问题讨论】:

  • matplotlib.dates.DateLocator()?
  • 我会试试的。还在寻找答案,谢谢!
  • 不是答案,但这些看起来不像 unix_timestamps。 1575254280000 对应于 51887 年的某个时间。你来自未来吗?
  • @DizietAsahi 哈哈。抱歉,我忘了说这是以毫秒为单位的 unix_time。

标签: python datetime matplotlib histogram


【解决方案1】:

我的感觉是,您需要使用numpy.histogram2d 计算直方图,然后将边缘转换为datetime 格式,最后绘制直方图与转换后的坐标。

# Test data
N = 2*24*60
df = pd.DataFrame({'unix_time':pd.date_range(start='2018-02-01', freq='1min', periods=N).strftime('%s').astype(int),
                   'value':np.random.normal(size=(N,))})

# compute the 2D histogram using numpy
H,xedges,yedges = np.histogram2d(df['unix_time'], df['value'], bins=[24,10])
# convert the x-edges into datetime format
to_datetime = np.vectorize(datetime.datetime.fromtimestamp)
xedges_datetime = to_datetime(xedges)

# plot the two cases side by side
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,3))
ax1.hist2d(df['unix_time'],df['value'], bins=[24,10])
ax1.set_title('unix_time')

ax2.pcolor(xedges_datetime, yedges, H.T)
ax2.set_title('datetime')
# pretty up the xaxis labels
ax2.xaxis.set_major_locator(loc)
ax2.xaxis.set_major_formatter(fmt)


fig.autofmt_xdate()
fig.tight_layout()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多