【问题标题】:Scatter plot segregate clusters by color plotly python散点图按颜色分隔集群 python
【发布时间】:2017-08-16 15:29:54
【问题描述】:

我正在使用 plotly(当我悬停时能够获取点信息)来可视化我的聚类散点图。我无法为使用 KMeans 生成的集群分配不同的颜色。在 matplotlib.pyplot(作为 plt)中绘制它时,我使用以下代码:

plt.scatter(restult[:,0], result[:,1], c=cluster_labels

cluster_labels 是:

n_clusters = 3
km = KMeans(n_clusters).fit(result)
labels = km.labels_

它工作得很好,但我需要胡佛信息。

这就是我到目前为止的情节:

trace = go.Scatter(
    x = result[:,0],
    y = result[:,1],
    mode = 'markers',
    text = index, # I want to see the index of each point
)
data = [trace]

# Plot and embed in ipython notebook!
py.iplot(data, filename='basic-scatter')

感谢您的帮助!

【问题讨论】:

    标签: python-2.7 cluster-computing plotly scatter-plot


    【解决方案1】:

    只是为了扩展 Maxmimilian 的方法 - 如果您使用的是 sklearn 版本 >=0.17,那么您需要重新调整您的数组,因为在 0.17 中不推荐使用传递一维数组。

    这是一个重塑的例子:

    x = df[df.columns[1]]
    x = x.values.reshape(-1,1)
    y = df[df.columns[2]]
    y = y.values.reshape(-1,1)
    
    kmeans = cluster.KMeans(n_clusters = 3, random_state = 0).fit(x, y)
    
    
    trace1 = go.Scatter(
    x = df[df.columns[1]],
    y = df[df.columns[2]],
    mode = 'markers',
    marker=dict(color=kmeans.labels_,
                size = 7.5,
                line = dict(width=2)
               ),
    text =  df.index,
    name='Actual'
    )
    

    【讨论】:

    • 那段代码什么也没做,它没有任何情节
    • 这只是伪代码。用您自己的数据替换 x 和 y 并从上面的答案中导入库...
    【解决方案2】:
    • 让我们使用 iris 数据集
    • kmeans 中的标签用作颜色 (marker=dict(color=kmeans.labels_)),就像在 matplotlib 中一样

    from sklearn import datasets
    from sklearn import cluster
    import plotly
    plotly.offline.init_notebook_mode()
    
    iris = datasets.load_iris()
    kmeans = cluster.KMeans(n_clusters=3, 
                            random_state=42).fit(iris.data[:,0:2])
    data = [plotly.graph_objs.Scatter(x=iris.data[:,0], 
                                      y=iris.data[:,1], 
                                      mode='markers',     
                                      marker=dict(color=kmeans.labels_)
                                      )
           ]
    plotly.offline.iplot(data)
    

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 2019-11-27
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      相关资源
      最近更新 更多