【问题标题】:How to combine plotly legends?如何结合情节传奇?
【发布时间】:2022-08-14 11:25:48
【问题描述】:

如何编辑情节图例,以便将“颜色”和“符号”合并为一个?

import pandas as pd 
import plotly.express as px
import numpy as np
from sklearn.decomposition import PCA


pca = PCA()

X_pca = pca.fit_transform(X)

fig = px.scatter(X_pca, x=0, y=1, color=df[\"subtype\"], width=600, height=600, color_discrete_sequence=[\"red\", \"orange\", \"brown\", \"green\"], title=\"Kernel PCA - tumor subtype vs normal\", symbol=df[\"subtype\"], symbol_sequence=[\'circle\', \'circle\', \'circle\', \'square\'])
fig.update_traces(marker=dict(size=5, line=dict(width=0.5, color=\'DarkSlateGrey\')), selector=dict(mode=\'markers\'))
fig.update_xaxes(automargin=True)
fig.update_yaxes(automargin=True)
fig.update_layout({\'plot_bgcolor\': \'rgb(240,240,240)\', \'paper_bgcolor\': \'rgb(240,240,240)\',})
fig.show()
fig.write_image(\"meth_subtype_pca.png\")

电流输出:

图例有\"color, symbol\"...\"kirp, kirp\" 等。我想用\"subtype\"...\"KIRP\" 替换它。

    标签: python plotly


    【解决方案1】:

    这个活动对我来说是新的;它是由使用 PCA 散点图指定符号引起的。我通过在reference 的示例中添加符号来确认相同的事件。似乎没有办法控制这一点,所以我自定义创建的图形,一个是采用重复的图例名称并将它们设置()为单个值。此外,图例标题是手动指定的。

    import pandas as pd 
    import plotly.express as px
    import numpy as np
    from sklearn.decomposition import PCA
    
    df = px.data.iris()
    X = df[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']]
    
    pca = PCA()
    
    X_pca = pca.fit_transform(X)
    
    fig = px.scatter(X_pca, 
                     x=0,
                     y=1,
                     color=df["species"],
                     width=600,
                     height=600,
                     color_discrete_sequence=["red", "orange", "brown", "green"],
                     title="Kernel PCA - tumor subtype vs normal",
                     symbol=df["species"],
                     symbol_sequence=['circle', 'circle', 'square']
                    )
    fig.update_traces(marker=dict(size=5, line=dict(width=0.5, color='DarkSlateGrey')), selector=dict(mode='markers'))
    fig.update_xaxes(automargin=True)
    fig.update_yaxes(automargin=True)
    fig.update_layout({'plot_bgcolor': 'rgb(240,240,240)', 'paper_bgcolor': 'rgb(240,240,240)',})
    
    # update
    for data in fig.data:
        data['name'] = list(set(data['name'].split(', ')))[0]
    fig.layout['legend']['title']['text'] = 'color'
    
    fig.show()
    #fig.write_image("meth_subtype_pca.png")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-10
      • 2021-01-08
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 2014-10-11
      • 1970-01-01
      • 2018-01-15
      相关资源
      最近更新 更多