Reputation: 17164
I have plotly3.6 installed in my office computer, which I can not upgrade. And I was trying to make sorted bar plots but it is failing to do so.
How can I do so?
My attempt:
def barplot(x,y):
data = [go.Bar(
x=x,
y=y,
marker={
'color': y,
'colorscale': 'Reds'
}
)]
layout = {
'xaxis': {
'tickvals': x,
'ticktext': [str(i) for i in x],
'tickangle': 40,
'type': "category",
'categoryorder': 'category ascending'
}
}
fig = go.FigureWidget(data=data, layout=layout)
return iplot(fig)
# plot
x = list('abcde')
y = [20,10,5,8,9]
barplot(x,y)
Related links: (This only works for plotly3.10, does not work for 3.6) How to plot sorted barplot in plolty3.10
Help is appreciated.
Upvotes: 1
Views: 61
Reputation: 27430
Here's a version of your function which does this... basically you just pre-sort the x
and y
values that you pass into go.Bar()
. Because x
is a list of strings in this case, the xaxis.type
is inferred to be "category"
and the order of the categories is by default the order in which the x
list is provided, so there's no need to fiddle with tickvals
or ticktext
.
import plotly.graph_objs as go
from plotly.offline import iplot
def barplot(x,y):
sorted_y = sorted(y)
sorted_x = [str(j) for i,j in sorted(zip(y,x))]
data = [go.Bar(
x=sorted_x,
y=sorted_y,
marker={
'color': y,
'colorscale': 'Reds'
}
)]
fig = go.FigureWidget(data=data)
return iplot(fig)
# plot
x = list('abcde')
y = [20,10,5,8,9]
barplot(x,y)
Upvotes: 1