如何将hist2d xaxis ticks设置为datetime格式?

2024-06-26 14:17:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我得到“TypeError:ufunc'isfinite'不支持输入类型,并且根据强制转换规则“safe”,无法将输入安全地强制为任何支持的类型”

我要绘制的数据:

The data I want to display

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

This is what I plotted if I put unixtime as xsticks

这是应该的情节 This is supposed to be

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()

Tags: 数据import类型datetimetimenppltarray
1条回答
网友
1楼 · 发布于 2024-06-26 14:17:19

我的感觉是您需要使用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()

enter image description here

相关问题 更多 >