I have a data table tb
that looks something like this, which I want to turn into a bar chart.
N X P
________ ______ ______
0 5 15.314
0 10 36.288
0 13 7.1785
1 5 18.182
1 10 40.997
1 13 8.9741
2 5 17.65
2 10 40.095
2 13 9.276
I want the bar chart to look something like this, but without needing to rearrange the table. What is the simplest way to do this?
Currently, my code to do it looks like this, but I expect there should be an easier way to manipulate it:
y = [tb.P(tb.X==5)' ; tb.P(tb.X==10)' ; tb.P(tb.X==13)'];
b = bar(y);
xlab = arrayfun(@num2str, Xlist, 'uniformoutput', false);
set(gca,'xticklabel',xlab);
leg = arrayfun(@num2str, Nlist, 'uniformoutput', false);;
legend(b,leg)
What would be the proper method for doing this?
You can do this a little easier with unique
and accumarray
:
[nValues, ~, nIndex] = unique(tb.N);
[xValues, ~, xIndex] = unique(tb.X);
bar(accumarray([xIndex nIndex], tb.P));
set(gca, 'XTickLabel', xValues);
legend(int2str(nValues));