In this post, we will see how to resolve 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 dataframedf
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 usingcolor_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!
Source: Stackoverflow.com
Leave a Review