0

Hi so I am trying to plot a dynamic bar graph with Y axis tick marks from -90 to 90. When I do this on a non-dynamic bar graph the tick labels display properly. As soon as I make it dynamic they are all over the place.

Hopefully someone can see where I have gone wrong..

% Generate a random vector of -90 to +90 to simulate pitch.

pitch = 90*rand(1) - 90*rand(1);

%Static bar graph, y tick marks are working here
subplot(2,1,1);
bar(pitch);
set(gca,'YLim',[-90.5 90.5]);
set(gca,'YTick',[-90,-45,0,45,90]);
title('Pitch');

%Dynamic bar graph, y tick marks are not working here
subplot(2,1,2);
barGraph = bar(pitch);
set(gca,'YLim',[-90.5 90.5]);
set(gca,'YTick',[-90,-45,0,45,90]);
title('Pitch');


 for j=1:1000,
     pitch = 90*rand(1) - 90*rand(1);
     set(barGraph,'YData',pitch);
     drawnow;
     pause(0.1);
 end
Shasam
  • 127
  • 2
  • 7
  • it seems to be a bug. have a look here http://www.mathworks.com/matlabcentral/answers/139521-bar-graph-plotting-off-of-axes – ironzionlion Aug 03 '14 at 14:06

2 Answers2

2

Method 1

Move the 2 set(gca.... lines into the loop, after set(....'YData'....) and before drawnow.

for jj=1:20
    pitch = 90*rand(1) - 90*rand(1);
    set(barGraph,'YData',pitch);
    set(gca,'YLim',[-90.5 90.5]);
    set(gca,'YTick',[-90,-45,0,45,90]);
    drawnow;
    pause(0.1);
end

Method 2

As @Dev-iL has suggested, use hold on to keep the axes properties through loops. But using hold on only raises a problem that if you run the script for more than 1 times, the bar plot will overlay with each other. Using hold off together will fix this issue.

hold on
for jj=1:20
    pitch = 90*rand(1) - 90*rand(1);
    set(barGraph,'YData',pitch);
    drawnow;
    pause(0.1);
end
hold off

Method 3 (not good)

Before the loop, set the property YDataSource to 'pitch'. Inside the loop, update the graph with refreshdata. Also requires hold on and hold off.

set(gca,'YLim',[-90.5 90.5]);
set(gca,'YTick',[-90,-45,0,45,90]);
set(barGraph, 'YDataSource', 'pitch');
hold on

for jj=1:20
    pitch = 90*rand(1) - 90*rand(1);
    refreshdata;
    pause(0.1);
end
hold off

The performance of this method is 2.5x slower than the former 2. Don't use it.

About the loop iterator j

j, as well as i, is one of the most commonly used loop iterator in many popular languages. But in Matlab, they are specifically assigned to the imaginary unit. It's OK to overwrite the default value of this special variable, but it is not good.

Use ii and jj instead.

Community
  • 1
  • 1
Yvon
  • 2,903
  • 1
  • 14
  • 36
1

Just add hold on before the loop. (I'm using MATLAB 2014a)

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
  • Also need to add `hold off` after the loop, if the script is to be run for more than 1 times; otherwise the graph will be overlayed unexpectedly. – Yvon Aug 03 '14 at 23:05