简体   繁体   English

plot如何根据plotly中的分类变量分

[英]How plot points based on categorical variable in plotly

I am using Plotly for visualization.我正在使用 Plotly 进行可视化。 I want to make plot, and give the points colors based on categorical variable.我想制作 plot,并根据分类变量给出分数 colors。

    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()

where Category is column in my dataframe. How can I do this kind of graph其中类别是我的 dataframe 中的列。我该怎么做这种图表

  • you have implied a data frame structure which I have simulated你暗示了我模拟的数据帧结构
  • it's simpler to use Plotly Express higher level API that graph objects使用Plotly表示图形对象的更高级别 API 更简单
  • have used to calls to px.scatter() to generate traces defined in your question.曾经调用px.scatter()来生成问题中定义的跟踪。 Plus have renamed traces in second call to ensure legend is clear and made them lines另外在第二次调用中重命名了痕迹以确保图例清晰并使它们成为线条
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
)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM