1

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?

pic1

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?

EBH
  • 10,350
  • 3
  • 34
  • 59
teepee
  • 2,620
  • 2
  • 22
  • 47

2 Answers2

1

I don't know if it's more simple for you, but you can also do this:

dat = sortrows(tb,[2 1]);
y = reshape(dat.P,numel(unique(dat.X)),[]).';
b = bar(y);
set(gca,'xticklabel',unique(dat.X));
legend(b,num2str(unique(dat.N)))

And if you have Matlab 2017a you can also use this example with categorical data, to set x-axis values from the call to bar.

EBH
  • 10,350
  • 3
  • 34
  • 59
1

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));
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • Thank you. This looks like a good way to do it. As an aside, what is the most robust way to keep track of how to refer to the next figure when you are making multiple plots (i.e. for figure(1), figure(2) etc. it seems like using figure(count) and then count=count+1 is not super robust). – teepee Jun 07 '17 at 22:54
  • @teepee: Best practice is to capture handles to figures, or any graphics object, and use those as targets for subsequent operations, like adding plots to an axes. For example: `hFigure = figure(); hAxes = axes(hFigure); hPlot = plot(hAxes, ...);` – gnovice Jun 08 '17 at 04:11