Resolved: Manually set color legend for Plotly line plot

In this post, we will see how to resolve Manually set color legend for Plotly line plot


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:

Best Answer:

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

If you have better answer, please add a comment about this, thank you!