Reputation: 127
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
Upvotes: 0
Views: 628
Reputation: 2993
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
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
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.
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.
Upvotes: 2