Search code examples
pythoncolorsplotlypalette

base the colors for go.Bar based on a specific columns values


How can I make a bar graph's color be based on a value of a column and pull those colors from a palette?For the following example, I would like to know how to base the colors off of the Category column. I would not know how many Categories ahead of time.

fig = go.Figure()
# create a bar graph with colors being different based on category
fig.add_trace(go.Bar(
                x=challenge_count_df["Challenge"],
                y=challenge_count_df["Count"],
                marker_color=challenge_count_df["Category"]
    )
)

If you could give me any help in figuring out how to maybe map the marker color based on the values of the Category column with colors from a palette, I'd greatly appreciate it.


Solution

  • You can do something like this. Use marker and provide dictionary with the Category column and the palette of your choice. Based on the value of the numbers in the palette, the colors will be close or farther apart within the palette. Hope this is what you are looking for.

    challenge_count_df = pd.DataFrame({'Challenge': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
                                      'Count' : [32, 22, 40, 12, 10, 60, 32, 22, 44, 90],
                                      'Category' : [1,2,3,4, 10, 15, 20, 25, 40, 80]})
    fig = go.Figure()
    # create a bar graph with colors being different based on category
    fig.add_trace(go.Bar(x=challenge_count_df["Challenge"], y=challenge_count_df["Count"],
        marker=dict(color = challenge_count_df["Category"], colorscale='viridis')
        )
    )
    

    Stabkoverflow not uploading pics for the moment, will upload it once it is back up and running. You can run the code and get the pic in any case