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

Viewed 118

Using K-Means from scikit learn, I clustered my dataframe into 3 clusters. I want to plot a line graph that will have multiple colors depending on the cluster it is in. How do I make gaps where there are supposed to be no data for a cluster?

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

plotting line graph

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

K-Means clustering linegraph plotted

1 Answers

Based on this link: https://plotly.com/python/line-charts/#connect-data-gaps

if you have NaN values where the cluster values are not supposed to be, it will not connect the gap by default. I would suggest resample().asfreq() to resample what looks to be a datetimeindex(?) and insert NaNs to ensure that the gaps are not connected.

Related