Search code examples
pythonplotlyplotly-python

Force distinct color for discrete values in plotly


If I pass in some discrete data into plotly, it will automatically populate all the values with some ~15 colors) (ex. {"1":blue, "2",:red, ..., "16": blue, "17":red, ...}). How can I ensure all discrete values have distinct colors?


Solution

  • If you have 26 or fewer colors, then you can use px.colors.qualitative.Alphabet. If you need more colors than that, you can construct a longer palette by appending together multiple color palettes:

    my_colors = px.colors.qualitative.Light24 + px.colors.qualitative.Dark24
    

    In this case, my_colors would have length 48. I believe all of the colors are distinct, though some are close to each other.

    For all possible rgb colors you could use the following:

    all_colors = [f"rgb({r},{g},{b})" for r in range(256) for g in range(256) for b in range(256)]
    

    And if you want n distinct colors roughly evenly distributed over all_colors, you can let k = floor(256^3 / n), and iterate through every kth element of all_colors