'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



Solution 1:[1]

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

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1