MATLAB Answers

Why do plotting functions like bar or barh take a long time to execute?

21 views (last 30 days)
I have a 1x600 vector of doubles, where each element represent the duration of a certain engineering process. I want to get a horizontal stacked bar graph which shows the duration of each process sequentially. For that I am using the following code
BHd --> 1x600 vector
BHd = [zeros(length(BHd),1), BHd];
figure(3)
barh(BHd', 'stacked');
However, I noticed that it takes a long time for barh function to run in this case (58.2 s). Are there any alternative ways of plotting the stacked bar graphs, that would take less time?
The plots should have the following format.
Btw, I am running MATLAB2017b on my computer

  3 Comments

jonas
jonas on 9 Aug 2018
You can do more or less the same ting with lines, instead of patches. See here.
You just increase the line width, and it looks like a bar. You can also plot the edges as a continous line.
theblueeyeswhitedragon
theblueeyeswhitedragon on 9 Aug 2018
It does not solve my problem, because I need each patch to have distinct colors from its neighbors. I tried using a loop for doing the plotting, where I take the sum of all previous elements and add to that number the duration of the n-th process. For instance, at the 53rd iteration:
xvals = sum(BHd(1:52)) : sum(BHd(1:52))+ BHd(53);
yvals = ones(size(xvals));
plot(xvals, yvals, 'Color', rand(3,1));
But this approach still takes considerable time to run.
jonas
jonas on 9 Aug 2018
You dont need a loop, plot accepts multiple inputs. In the thread I linked, each segment has its own handle, and its own properties. I can show you a bit later today if no one else does

Sign in to comment.

Accepted Answer

jonas
jonas on 9 Aug 2018
Edited: jonas on 9 Aug 2018
I would guess that barh is slow because it creates 600 different patch objects, each with a different handle. Try this solution with a single surface object.
%%Method 1, SURF
n=10;
figure;
subplot(1,2,1)
x=rand(1,n);
tic
X=cumsum(x);
X=[0 X;0 X];
Y=[1.1.*ones(1,n+1);0.9.*ones(1,n+1)];
Z=rand(1,n+1);
Z=[Z;Z];
surf(X,Y,Z)
view([0 90])
set(gca,'ylim',[-2 3])
t1=toc;
%%Method 2, BARH
subplot(1,2,2)
tic
x=[nan(length(x),1)'; x];
barh(x, 'stacked');
t2=toc;
%%Display performance
t2/t1
ans =
2.9408
so surf takes 1/3 of the time in this case. If you increase the number of elements, then the difference will increase further. At 600 elements, they differ by a factor of 500 on my machine.
You can use a different colormap and a different method for calculating the Z-values, if you need more distinct color differences.
I'm guessing you cannot increase the performance further by using line objects, as I suggested in the comments. You would have to create 600 line objects, which would hurt the performance.

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!