Good afternoon I'm trying to combine some bar graphs I have created. I tried with 'hold on' but it doesn't work, maybe because I have used the for loop.

2 views (last 30 days)
Good afternoon I'm trying to combine some bar graphs I have created. I tried with 'hold on' but it doesn't work, maybe because I have used the for loop. Here is my code and the results I get. The graphs are good, but I want them in a single graph. Thank you.
for i = 1:m
hold on
if (p(i) >= 10) && (p(i) < 20) %clasa 2
%create MATLAB bar chart
hold on
fig = figure;
bar(i, v(i), 'r');
hold on
bar(i,c(i),'b');
%add legend
legend('non-ground points','ground points');
end;
end;

Accepted Answer

Adam
Adam on 2 May 2017
Edited: Adam on 2 May 2017
Move
fig = figure;
outside the loop. You are creating a new figure within the loop, that is why they all go in different figures. You should also move the legend command after the for loop - you only want one legend.
You should get used to using explicit handles to things like axes though - e.g.
hAxes = axes( fig );
bar( hAxes, i, v(i), 'r');
hold( hAxes, 'on' );
etc etc.
Then it is explicit and clear in your code which axes you are referring to. In your code you have all these 'hold on' commands but it is not always immediately obvious (as is the reason you are asking the question) from looking at the code which axes are actually being applied to by the command. Don't just keep throwing in extra hold commands in different places if they don't seem to be doing anything! It just clutters up your code for you.
Save yourself the issues of commands being applied to unexpected axes and get used to using the explicit handles, it will save you a lot of confusion!

More Answers (1)

Rik
Rik on 2 May 2017
You can vectorize this and then plot the resulting matrix/vectors in one go with bar.
Hints:
  • If you can't get a vectorized solution, try to make vectors in a for-loop.
  • Depending on the x-values, your plot may be spaced really weird. You can avoid this by generating a new x-vector and using the original values to create category labels.
  • Read the documentation for bar to find out how you can get the behavior you want.
If you can't get it done, try to describe the point where you have errors or don't understand how the functions work. Especially the grouping can be tricky.

Categories

Find more on Graphics Object Properties in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!