我有一個(示例)資料框,如下所示:
time event type
0 2022-01-22 10:35:00 a
1 2022-01-22 11:37:00 a
2 2022-01-22 22:22:00 b
3 2022-01-22 12:05:00 b
4 2022-01-22 10:09:00 c
5 2022-01-22 10:57:00 a
6 2022-01-22 11:36:00 c
7 2022-01-22 09:45:00 a
我想創建一個 3D 曲面圖,顯示每小時發生的每種型別的事件數量。繪圖的軸應該是:
X: hour
Y: event type
Y: number of events
我希望在X軸上看到:9, 10, 11, 12 ,22,在Y軸上:a, b, c。對于 Z 軸,這些值應反映每小時每種型別的事件數。例如X=10, Y=a, Z=2
我查看了檔案和各種示例,但找不到并回答
uj5u.com熱心網友回復:
這需要兩個任務。首先,您必須聚合資料以計算唯一對hour- event type,然后從聚合的hour- event type-event count資料創建 3D 圖:
from matplotlib import pyplot as plt
from matplotlib.ticker import MaxNLocator
import pandas as pd
import numpy as np
#test data
np.random.seed(123)
n = 10
start = pd.to_datetime("2021-04-21")
end = pd.to_datetime("2021-04-23")
n_minut = ((end - start).days 1) * 24 * 60
date_range = pd.to_timedelta(np.random.randint(0, n_minut, n), unit="minute") start
df = pd.DataFrame({"time": date_range, "event type": np.random.choice(list("abcde"), n)})
#count event types per hour
plot_df = df. groupby([df["time"].dt.hour, df["event type"]]).size().reset_index(name="event count")
#transcribe categorical data in column "event type" into integer values
#idx contains the list of event types according to their integer numbers
val, idx = plot_df["event type"].factorize()
plot_df["event_num"] = val
#generate evenly spaced x- and y-values
x_range = np.arange(24)
y_range = np.arange(idx.size)
#and create x-y arrays for the 3D plot
X, Y = np.meshgrid(x_range, y_range)
#and fill z-values with zeros
Z = np.zeros(X.shape)
#or the event count, if exists
Z[plot_df["event_num"], plot_df["time"]] = plot_df["event count"]
#create figure with a 3D projection axis
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.plot_surface(X, Y, Z)
ax.zaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_yticks(y_range, idx)
ax.set_ylabel("event type")
ax.set_xlabel("time (in h)")
ax.set_zlabel("count")
plt.show()
樣本輸出:

然而,眾所周知,matplotlib 有時會出現以正確的可見性順序繪制曲面的問題。根據您的資料,使用散點圖可能會更好:
...
X, Y = np.meshgrid(x_range, y_range)
Z = np.full(X.shape, np.nan)
Z[plot_df["event_num"], plot_df["time"]] = plot_df["event count"]
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.scatter(X, Y, Z)
ax.zaxis.set_major_locator(MaxNLocator(integer=True))
...

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/419617.html
標籤:
上一篇:故事板中較低的Z視圖索引
