如何在 plotly 中基于分类变量绘制点

How plot points based on categorical variable in plotly

我正在使用 Plotly 进行可视化。我想画图,并根据分类变量给点颜色。

    fig = go.Figure()
   
    fig.add_trace(go.Scatter(x=df.Predicted, y=df.Predicted,colors='Category',mode='markers',
                        
                        ))
    fig.add_trace(go.Scatter(x=df.Predicted, y=df.real ,   colors='Category'         
                      ))
    fig.show()

其中类别是我的数据框中的列。这种图要怎么做

  • 你暗示了我模拟的数据帧结构
  • 使用 Plotly Express 更高级别 API 比 graph 对象
  • 更简单
  • 曾经调用 px.scatter() 来生成问题中定义的跟踪。另外在第二次调用中重命名了轨迹以确保图例清晰并使它们成为线条
import numpy as np
import pandas as pd
import plotly.express as px

df = pd.DataFrame(
    {
        "Predicted": np.sort(np.random.uniform(3, 15, 100)),
        "real": np.sort(np.random.uniform(3, 15, 100)),
        "Category": np.random.choice(list("ABCD"), 100),
    }
)

px.scatter(df, x="Predicted", y="Predicted", color="Category").add_traces(
    px.line(df, x="Predicted", y="real", color="Category")
    .for_each_trace(
        lambda t: t.update(name="real " + t.name)
    )  # make it clear in legend this is second set of traces
    .data
)