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]
)]
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