问题
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.
NOTE: https://community.plot.ly/t/sort-bars-in-bar-chart-by-value-and-have-each-bar-with-a-different-color/14562
Did not worked for me.
Data
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'])
Using pandas (gives sorted barplot)
df1 = df.groupby('store')['sales'].sum().sort_values()
df1.plot.bar()
Using plotly3.10 (gives unsorted barplot) (How to fix this?)
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)
outputs
Question
How to get sorted barplot using plotly3.10 ?
Related link
https://community.plot.ly/t/sort-bars-in-bar-chart-by-value-and-have-each-bar-with-a-different-color/14562
Did not work for me.
回答1:
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)
来源:https://stackoverflow.com/questions/57642439/how-to-plot-sorted-barplot-in-plolty3-10