如何根据聚类标签绘制具有多种颜色的单线

How to plot single line with multiple colors in plotly based on cluster label

使用 scikit learn 中的 K-Means,我将数据框聚类为 3 个聚类。我想绘制一个折线图,根据它所在的集群,它有多种颜色。如何在集群应该没有数据的地方留出空白?

kmeans = KMeans(n_clusters=3)
kmeans.fit(nocutoff_diffdf_windowed2d)
y_kmeans = kmeans.predict(nocutoff_diffdf_windowed2d)
plt.scatter(nocutoff_diffdf_windowed2d[:, 0], nocutoff_diffdf_windowed2d[:, 1], c=y_kmeans)

centers = kmeans.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, alpha=0.5);

绘制折线图

fig = go.Figure()

for i in range(0, 3):
    df = X_nocutoff_diffdf_windowed[y_kmeans == i]
    fig.add_trace(go.Scatter(
        x=df.index,
        y=df['total'],
    ))

# fig = px.line(X_nocutoff_diffdf_windowed, x=X_nocutoff_diffdf_windowed.index, y="total", title='linegraph of total over time', color=y_kmeans)
fig.show()

基于此link:https://plotly.com/python/line-charts/#connect-data-gaps

如果簇值不应该是 NaN 值,默认情况下它不会连接间隙。我建议 resample().asfreq() 对看起来像 datetimeindex(?) 的内容重新采样并插入 NaN 以确保间隙没有连接。