Reputation: 17154
I have been trying to plot sorted barplot in plotly for some stores sales data, but whatever I try it gives me the unsorted data. How to plot the sorted barplot using plotly.
Did not worked for me.
import numpy as np
import pandas as pd
import plotly
import plotly.offline as py
import plotly.graph_objs as go
from plotly.offline import plot, iplot, init_notebook_mode
init_notebook_mode(connected=False)
print([(x.__name__,x.__version__) for x in [np, pd,plotly]])
url = "https://github.com/bhishanpdl/Datasets/blob/master/store_item_demand/train_store_item_demand.csv?raw=true"
df = pd.read_csv(url, parse_dates=['date'],index_col=['date'])
df1 = df.groupby('store')['sales'].sum().sort_values()
df1.plot.bar()
def barplot(x,y):
data = [go.Bar(
x=x,
y=y,
marker={
'color': y,
'colorscale': 'Reds'
}
)]
layout = {
'xaxis': {
'tickvals': x,
'ticktext': ['store ' + str(i) for i in x],
'tickangle': 40
}
}
fig = go.FigureWidget(data=data, layout=layout)
return iplot(fig)
# plot
df1 = df.groupby('store')['sales'].sum().sort_values()
x = df1.index.values
y = df1.values
barplot(x,y)
How to get sorted barplot using plotly3.10 ?
Did not work for me.
Upvotes: 3
Views: 358
Reputation: 27370
The correct key to use for this is layout.xaxis.categoryorder
, with the value "total ascending"
, but it only applies when the layout.xaxis.type
is "category"
. This happens automatically if your x
array contains strings, but if your x
contains only numbers you'll have to set it manually.
Here is a version of your barplot
function as recommended:
def barplot(x,y):
data = [go.Bar(
x=x,
y=y,
marker={
'color': y,
'colorscale': 'Reds'
}
)]
layout = {
'xaxis': {
'tickvals': x,
'ticktext': ['store ' + str(i) for i in x],
'tickangle': 40,
'type': "category",
'categoryorder': 'total ascending'
}
}
fig = go.FigureWidget(data=data, layout=layout)
return iplot(fig)
Upvotes: 2