Manually set color legend for Plotly line plot

Question:

I would like to fix colors for my legend in a plotly line graph. Basically, I have a dataframe df in which there is a column Sex. I already know that my dataframe will hold only 3 possible values in that column.

So I would like to fix colors ie. Green for Male, Blue for Female and Yellow for Other. This should also hold true when there are no occurrences in the df for one category i.e. Male.

Currently, my code auto-defaults colors. For ex: If df contains all categories, it sets Blue for Male, Yellow for Female, Green for Other. But when, df only holds values containing Male and Female, the color preferences change, thereby losing consistency.

Code is as follows:

df = pd.DataFrame(...)

lineplot = px.line(
        df, 
        x="Date", 
        y='Ct', 
        color='Sex',
        title=f"Lineplot to keep track of people across time"
    )
lineplot.show()
Asked By: Krishna

||

Answers:

You can define the colours individually using color_discrete_map argument. Ref and still keep the specific color which we set manually:

import plotly.express as px
import pandas as pd

df = pd.DataFrame(dict(
    Date=[1,2,3],
    Male   = [1,2,3],
    Female = [2,3,1],
    Others = [7,5,2]
))


fig = px.line(df, x="Date", y=["Male",
                              # "Female", comment this type for testing color
                               "Others"],
             color_discrete_map={
                 "Male": "#456987",
                 "Female": "#147852",
                 "Others": "#00D",
                 
             })

fig.show()

output:

img

Answered By: Mario
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.