Speed up plotting of multiple lines
13 views (last 30 days)
Show older comments
Dear All Community members,
I have a question concerning speeding up the function plot.
I want to plot several (72835) lines in order to create a hexagonal pattern, where each line will be colored depending on its value represented in a third vector.
The coordinates of the lines are given in two matrices, ‘x’ and ‘y’, while the color depends on the matrix ‘yo’. These matrices are attached.
Example: Line 1
X-coordinates are given in x11 and x12 in matrix 'x'.
Y-coordinates are given in y11 and y21 in matrix 'y'.
The line has a blue-violet color palette. See Figure below.
The code I am using is given below, in addition to a plot of all the lines colored.
figure
for i=1:size(x,2)
plot(x(:,i), y(:,i), 'LineWidth', 2.5, 'Color', yo(i,:))
axis square ;
hold on
end
hold off
colormap(map)
colorbar('Position', [0.8 0.25 0.04 0.6]);
caxis([11 334])
It is very time-consuming to run, and the plot is really slow to respond if I want to zoom or etc.
Is it possible to plot this differently? E.g., Using a patch objective?
Any help is deeply appreciated.
0 Comments
Accepted Answer
Voss
on 9 Feb 2023
Here's an idea: plot all the line segments of a given color together as one line object. That way you have 2745 lines instead of 72835. That speeds it up quite a bit. You could speed it up more by reducing the number of unique colors in yo. The colorbar suggests you only need 12 unique colors.
load Data
nans = NaN(1,size(x,2));
xx = [x; nans];
yy = [y; nans];
[uyo,~,jj] = unique(yo,'rows');
for ii = 1:size(uyo,1)
idx = jj == ii;
xx_p = xx(:,idx);
yy_p = yy(:,idx);
line(xx_p(:),yy_p(:),'LineWidth',2.5,'Color',uyo(ii,:));
end
axis square
colormap(map)
colorbar('Position', [0.8 0.25 0.04 0.6]);
caxis([11 334])
Note that I call axis square once after the loop instead of inside the loop. That helps with speed too.
I'm also using line instead of plot for speed. If using plot as in your original, you could speed it up by calling hold on once before the loop and hold off once after the loop. But hold doesn't apply when using line.
More Answers (0)
See Also
Categories
Find more on Polygons 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!