# Sort stacked bar chart according to total height

I would like to sort stacked bar chart in descending order after stacking up all numbers. In other words, I want to sort according to total height. I am aware of \pgfplotstablesort but in my case there are multiple columns, that is, Proc1 and Proc2. So I cannot use [sort key] option until all numbers are stacked up. How can I do it?

Tex file:

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

Function,Proc1,Proc2
Sub,3,4
Div,2,3
}{\data}

\begin{tikzpicture}
\begin{axis}[
cycle list=Dark2,
ybar stacked,
ymin=0,
xtick=data,
xtick pos=left,
ytick pos=left,
axis lines=left,
xticklabels from table={\data}{Function},
x tick label style={rotate=45, anchor=north east, inner sep=0mm},
ylabel=Elapsed seconds,
xlabel=Function,
legend pos=outer north east,
legend style={draw=none},
enlarge x limits=0.1,
]
\pgfplotstablegetcolsof{\data}
\pgfmathtruncatemacro\numberofcols{\pgfplotsretval-1}
\foreach \i in {1,...,\numberofcols} {
\addplot+ [draw opacity=0] table [y index=\i, x expr=\coordindex] {\data};
}
\end{axis}
\end{tikzpicture}

\end{document}


You were absolutely on the right track. To do what you want you "simply" need to create another column where the sum of the data is stored and then use this column as sort key.

For details please have a look at the comments in the code.

% used PGFPlots v1.16
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.3}
Function,Proc1,Proc2
Sub,3,4
Div,2,3
}{\data}
% sort the table
\pgfplotstablesort[
% for that we need to create another column to create the "total" value ...
create on use/sum/.style={
create col/expr={
\thisrow{Proc1} + \thisrow{Proc2}
},
},
% ... which we then use to sort the table
sort key=sum,
% the sorted table is then stored in \dataSorted', which of course then
% has to be used everywhere in the axis' environment
]{\dataSorted}{\data}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
cycle list=Dark2,
ybar stacked,
ymin=0,
xtick=data,
xtick pos=left,
ytick pos=left,
axis lines=left,
xticklabels from table={\dataSorted}{Function},
x tick label style={rotate=45, anchor=north east, inner sep=0mm},
ylabel=Elapsed seconds,
xlabel=Function,
legend pos=outer north east,
legend style={draw=none},
enlarge x limits=0.1,
]
\pgfplotstablegetcolsof{\dataSorted}
\pgfmathtruncatemacro\numberofcols{\pgfplotsretval-1}
\foreach \i in {1,...,\numberofcols} {
\addplot table [y index=\i, x expr=\coordindex] {\dataSorted};
}
\end{axis}
\end{tikzpicture}
\end{document}


• But what if there are more than two columns, that is, Proc1, Proc2, ..., ProcN? How can I sum them in a loop? – Shibli Apr 26 '18 at 11:39
• – Stefan Pinnow May 1 '18 at 15:40