Sort bars in bar chart by value and have each bar with a different color

here’s an example code to create bar chars in plotly python. This code create the bars in alphabetic order, but I would like it to create in increasing order of y value, so ‘orangutans’ bar first, then ‘giraffes’ and then ‘monkeys’. Also, I would like to have the bars colored each with a different color automatically instead of manually setting colors of these bars. How should I do?

import plotly.plotly as py
import plotly.graph_objs as go

data = [go.Bar(
x=[‘giraffes’, ‘orangutans’, ‘monkeys’],
y=[20, 14, 23]
)]

py.iplot(data, filename=‘basic-bar’)

Not sure if this is the best solution but I think it’s pretty easy to sort the lists in Python.
Here’s the code:

x=['giraffes', 'orangutans', 'monkeys']
y=[20, 14, 23]
sortx = [x for _,x in sorted(zip(y,x))]
sorty = sorted(y)
data = [go.Bar(
        x=sortx,
        y=sorty
        )]

py.iplot(data)

In addition to @caiyij nice solution, you can also control the display order of categories on an axis using the categoryorder/categoryarray properties of layout.xaxis.

You can set the color for each bar independently by passing an array to the bar.marker.color property. If this is an array of numbers, the color will be computed from a colorscale, which can be customized in bar.marker.colorscale. One nice thing to do in cases like this is the color the bars based on their height

For example:

import plotly.plotly as py
import plotly.graph_objs as go

xs = ['giraffes', 'orangutans', 'monkeys']
ys = [20, 14, 23]
data = [go.Bar(
    x=xs,
    y=ys,
    marker={
        'color': ys,
        'colorscale': 'Viridis'
    }
)]

layout = {
    'xaxis': {
        'categoryorder': 'array',
        'categoryarray': [x for _, x in sorted(zip(ys, xs))]
    }
}

fig = go.FigureWidget(data=data, layout=layout)
fig

Hope that helps!
-Jon

1 Like