Coloring bar plots according bins from values in plot

Hi all,
I am working on a project and i need help with adding colors according to bins of values for the plot. Please help with how i can create the bins and link with colors and then add to my plot.

Hi @Jason4,

Welcome to the forums! Have you seen the Customizing Individual Bar Colors example? If that doesn’t help, could you include an example of what you’ve tried so far and description of what you’d like the bars to look like?

-Jon

HI @jmmease thanks for your response, but what i would actually like it to color my bars depending on a bin for example :

grades:

8-10: green
6-7:yellow
4-5:orange
0-3:red

So i would like to colour the bars based on some bins not just randomly.

Thanks

Hi @Jason4,

Here are two ways you could go about this.

  1. Create a color array with the color string corresponding to each bar.
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode()
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 5, 8, 3, 5, 8, 10, 3, 1, 8]

def get_color(v):
    if v <= 3:
        return 'red'
    elif v <= 5:
        return 'orange'
    elif v <= 7:
        return 'yellow'
    else:
        return 'green'

colors = [get_color(v) for v in y]
    
fig = go.Figure()
fig.add_bar(x=x, y=y, marker={'color': colors})
iplot(fig)

  1. Specify the color as a numeric array and then configure the colorscale to display the colors you want.
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode()
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 5, 8, 3, 5, 8, 10, 3, 1, 8]

    
fig = go.Figure()
fig.add_bar(
    x=x, y=y, marker={'color': y,
                      'colorscale': [[0, 'red'],
                                     [0.5, 'red'],
                                     [0.5, 'green'],
                                     [1, 'green']],
                      'showscale': True})
iplot(fig)

See https://plot.ly/python/colorscales/#custom-discretized-heatmap-colorscale for an example of configuring a discrete colorscale.

Hope that helps,
-Jon

1 Like

Thanks @jmmease. That was very resourceful.