简体   繁体   中英

How plot points based on categorical variable in plotly

I am using Plotly for visualization. I want to make plot, and give the points colors based on categorical variable.

    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

  • you have implied a data frame structure which I have simulated
  • it's simpler to use Plotly Express higher level API that graph objects
  • have used to calls to px.scatter() to generate traces defined in your question. 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
)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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