【问题标题】:Plotly python scatterplot matrix column names in hovertemplate在悬停模板中绘制python散点图矩阵列名
【发布时间】:2021-09-03 07:32:19
【问题描述】:

在 python 中,我创建了一个绘图对象散点图矩阵,如下所示:

eval_columns = ['col1', 'col2', 'etc']
fig = go.Figure(data=go.Splom(
            dimensions=[dict(label=col, values=df[col]) for col in eval_columns],
            showupperhalf=False,
            text=df['col3'],
            marker=dict(color=df['col3'],
                        showscale=False, 
                        line_color='white', line_width=0.5),
            ))

生成的散点图矩阵中的悬停标签默认显示 (x,y) 值。 我想在 x 和 y 前面添加相应列的名称。 我该如何管理?

关于悬停模板的文档说:可以在悬停模板定义中访问每个可以指定的每个点的属性。然而,列名不是 per_point 属性。

关于如何做到这一点的任何想法?我知道 px.scatter_matrix 会自动将列名分配给悬停标签,但是我需要使用 go.Splom。

【问题讨论】:

    标签: python plotly


    【解决方案1】:

    悬停模板自动设置在px.scatter_matrix()中,所以如果你得到它的数据结构,你会发现悬停模板的描述,你可以应用到go.Splom()official reference 中的示例支持这一点。

    import plotly.graph_objects as go
    import pandas as pd
    
    df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris-data.csv')
    
    # The Iris dataset contains four data variables, sepal length, sepal width, petal length,
    # petal width, for 150 iris flowers. The flowers are labeled as `Iris-setosa`,
    # `Iris-versicolor`, `Iris-virginica`.
    
    # Define indices corresponding to flower categories, using pandas label encoding
    index_vals = df['class'].astype('category').cat.codes
    
    fig = go.Figure(data=go.Splom(
                    dimensions=[dict(label='sepal length',
                                     values=df['sepal length']),
                                dict(label='sepal width',
                                     values=df['sepal width']),
                                dict(label='petal length',
                                     values=df['petal length']),
                                dict(label='petal width',
                                     values=df['petal width'])],
                    text=df['class'],
        hovertemplate='%{xaxis.title.text}=%{x}<br>%{yaxis.title.text}=%{y}',
                    marker=dict(color=index_vals,
                                showscale=False, # colors encode categorical variables
                                line_color='white', line_width=0.5)
                    ))
    
    
    fig.update_layout(
        title='Iris Data set',
        dragmode='select',
        width=600,
        height=600,
        hovermode='closest',
    )
    
    fig.show()
    

    【讨论】:

    • 数据结构会在fig.data中输出,所以如果你检查它,你将能够更好地理解它。如果您觉得我的回答有帮助,请点击对勾接受回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 2014-11-09
    • 2020-07-25
    相关资源
    最近更新 更多