Search code examples
pythonplotlyplotly-python

In plotly, the continuous int variable automatically becomes a colorbar, so how do I make it a legend instead of a colorbar?


import pandas as pd
import plotly.graph_objs as go
import plotly.express as px
import numpy as np
import random

df = pd.DataFrame()
df["x"] = np.sin(np.arange(100))
df["y"] = np.sin(np.arange(-100,100,2))
df["z"] = 2*np.sin(np.arange(100))
_ = []
for i in range(100):
    _.append( random.choice([1,2,3]))
    # _.append( random.choice(["A","B","C"]))

df["type"] = _

fig = px.scatter_3d(data_frame = df, x="x", y="y", z="z", color="type")
fig.show()

Above code shows it.

enter image description here

It automatically generates a color bar for "types - 1,2,3"

But if I change "types" as ["A", "B", "C"], it shows below.

enter image description here

it automatically generates a legend, not a color bar.

I want to make a legend for [1,2,3], not a color bar. like the below image.

enter image description here

But I cannot find what option is for it.


Solution

  • @PaulH answered it.

    I changed datatype as "object" and make legend as ordered.

    code is below.

    df["type"]=df["type"].astype("object")
    fig = px.scatter_3d(data_frame = df, x="x", y="y", z="z", color="type", 
    
    category_orders={"type" : [1,2,3]}) # this line is for ordered legend.