1

I have a bar chart in plotly that I have produced, however, it is not in any type of order. How would I sort to ascending or descending?

enter image description here

What I am doing:

fig = px.bar(data, x='Old_SKU', y='u_power')
fig = data.sort_values('u_power', ascending=True)
fig.show()
Lynn
  • 4,292
  • 5
  • 21
  • 44
  • 1
    In order for this to make any sense you will have to share a [sample of your data](https://stackoverflow.com/questions/63163251/pandas-how-to-easily-share-a-sample-dataframe-using-df-to-dict/63163254#63163254) – vestland Feb 08 '21 at 19:34

1 Answers1

1

I'm not sure what your desired output is, or what your data looks like. In any case fig in plotly terms is normaly a plotly figure object. When you're running fig = data.sort_values('u_power', ascending=True) you're not building a figure, but sorting a dataframe. So far I can only imagine that you'd like to sort a dataset that looks like this:

enter image description here

... into this:

enter image description here

Or maybe you're expecting a continuous increase or decrease? In that case you will have to share a dataset. Nevertheless, with a few tweaks depending on your dataset, the following snippet should not be far from a working solution:

import plotly.express as px
import numpy as np
import pandas as pd
var = np.random.randint(low=2, high=6, size=20).tolist()
data = pd.DataFrame({'u_power':var,
                   'Old_SKU':np.arange(0, len(var))})

# fig = px.bar(data, x='Old_SKU', y='u_power', barmode='stack')
fig = px.bar(data.sort_values('u_power'), x='Old_SKU', y='u_power', barmode='stack')
fig.show()
vestland
  • 55,229
  • 37
  • 187
  • 305
  • 1
    Perfect yes . Sorry I need to share the actual data. I would like a continuous increase. I will play around w the code you provided. Thank you – Lynn Feb 08 '21 at 21:40
  • 1
    @Lynn Thank you for your swift feedback and for accepting my answer. If you haven't already, then please invest the three minutes it will take to learn the approach in my link above. It will save you tons of time trying to get useful answers to your future questions. Happy coding! – vestland Feb 08 '21 at 21:48
  • 1
    I will. Thank you – Lynn Feb 08 '21 at 21:55