python - 使用 Plotly 自定义标签

标签 python pandas cluster-analysis plotly k-means

我正在尝试自定义悬停时显示的数据标签: enter image description here 这是给我上面输出的代码:

import pandas as pd
import plotly.plotly as py
import plotly.graph_objs as go

# Create random data
labels = ['A', 'B', 'C']
N = 20
df = pd.DataFrame(index = range(N))
standardized_cols = []

for col in labels:
    df[col] = np.random.randn(N)
    standardized_colname  =  col + "_standardized"
    standardized_cols.append(standardized_colname)
    df[standardized_colname] = (df[col]-df[col].mean())/df[col].std()

# Cluster
c = KMeans(n_clusters=3, random_state=1).fit(df[standardized_cols]).labels_

# Plot
trace = go.Scatter3d(
    x=df.A_standardized,
    y=df.B_standardized,
    z=df.C_standardized,

    mode='markers',
    marker=dict(
        size=5,
        color=c,              
        colorscale='Viridis',   
    ),
    name= 'test',
    text= c
)

data = [trace]

fig = go.Figure(data=data, layout=layout)
iplot(fig)

我的数据: enter image description here ]

该图表显示了标准化列的聚类。 但是,当将鼠标悬停在数据上时,我希望看到标签中的非标准化数据,即类似于

A: 0,999
B: 0,565
C: 0,765
Cluster: 2

我进行了实验,但不知道如何实现这一目标。这可能吗?

最佳答案

您可以进行一些列表理解并添加您想要的任何列文本请参阅下面的示例(注意,我正在离线绘制):

# data
np.random.seed(1)
labels = ['A', 'B', 'C']
N = 20
df = pd.DataFrame(index = range(N))
standardized_cols = []

for col in labels:
    df[col] = np.random.randn(N)
    standardized_colname  =  col + "_standardized"
    standardized_cols.append(standardized_colname)
    df[standardized_colname] = (df[col]-df[col].mean())/df[col].std()

c = KMeans(n_clusters=3, random_state=1).fit(df[standardized_cols]).labels_

plotly :

import plotly as py
import plotly.graph_objs as go


trace = go.Scatter3d(
    x=df.A_standardized,
    y=df.B_standardized,
    z=df.C_standardized,

    mode='markers',
    marker=dict(
        size=5,
        color=c,              
        colorscale='Viridis',   
    ),
    name= 'test',

    # list comprehension to add text on hover
    text= [f"A: {a}<br>B: {b}<br>C: {c}" for a,b,c in list(zip(df['A'], df['B'], df['C']))],
    # if you do not want to display x,y,z
    # hoverinfo='text'


)


layout = dict(title = 'TEST',)

data = [trace]
fig = dict(data=data, layout=layout)

py.offline.plot(fig, filename = 'stackTest.html')

enter image description here

您可以修改列表理解以显示您想要的任何内容

如果您不想显示x,y,z,请添加hoverinfo='text'

关于python - 使用 Plotly 自定义标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54421402/

相关文章:

javascript - 如何在 GAE 中使用 app.yaml 获取适用于静态文件的任何 url?

python - Pandas groupby 函数中的 secondary_y 范围

audio - 可能取决于距离的中餐馆流程

python - 如何在sklearn中打印聚类结果

python - scrapy中如何处理302重定向

python - Kivy - 在其他屏幕中创建的访问实例

python - 如何使用 Python pandas 验证日期?

python - 在 Pandas 数据框中随机插入 NA 的值 - 没有行完全丢失

algorithm - 使用比例阈值进行聚类

python - 在 Pandas 中,找到每组中最小值大于值的行