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 dataframe
dfin 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
Femaleand Yellow for
Other. This should also hold true when there are no occurrences in the
dffor one category i.e.
Currently, my code auto-defaults colors. For ex: If
dfcontains all categories, it sets Blue for Male, Yellow for Female, Green for Other. But when,
dfonly 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_mapargument. Ref and still keep the specific color which we set manually:
If you have better answer, please add a comment about this, thank you!