How to sort Plotly bar chart in descending order
Asked Answered
J

2

11

I have created a basic bar chart in plotly that I would like to sort by descending order. enter image description here

I couldn't find an easy way to specify this in the plotly syntax, so I tried modifying the dataframe with Pandas. This also hasn't worked.

My code is below:

import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd


df = pd.read_csv('C:/Users/Documents/Python/CKANMay.csv')
sd = df.nlargest(3,'Views')
fd = sd.sort_values(by='Views', ascending = False)


my_data = [go.Bar( x = fd.Views, y = fd.Publisher, orientation = 'h')]
my_layout = ({"title": "Most popular publishers",
                       "yaxis": {"title":"Publisher"},
                       "xaxis": {"title":"Views"},
                       "showlegend": False})

fig = go.Figure(data = my_data, layout = my_layout)

py.iplot(fig)

I would like to invert the bar chart, so that the column with the greatest value is on the top. Appreciative for any assistance.

Jari answered 22/6, 2019 at 9:14 Comment(2)
Can you try 'ascending=True`? Plotly just plots the values in the same order as the come.Geter
Hah, yep that did it. I assumed True was the default value, so didn't even try that.Jari
S
21

Add this to update your figure:

fig.update_layout(barmode='stack', xaxis={'categoryorder':'total descending'})
Saccharose answered 22/6, 2020 at 5:11 Comment(0)
W
11

Update your layout with this:

fig.update_layout(yaxis=dict(autorange="reversed"))

source here

Example:

enter image description here

Withdrew answered 2/8, 2022 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.