Changing colour of plot every time X data changes direction

조회 수: 6 (최근 30일)
Jason
Jason 2024년 10월 16일
답변: Umar 2024년 10월 16일
Hello, I have a set of data (50k lines) representing a raster scan so there are several occurrances of the position zero (=X in my data).
When I plot this, the whole plot is the same colour. I want to be able to change the colour once the x Pos changes direction (So everytime it reaches a zero, but there are sometimes 2 zeros).
Im not too sure where to start with this one.
This is my current data plotted:

채택된 답변

Star Strider
Star Strider 2024년 10월 16일
It would help to have the actual data, and an explanation of how you are plotting them, with code.
The reason is that if there are multiple instances of 0 in ‘xpos’ thern there should be ‘reverses’ in the plot, for example —
x = [0 1 2 3 0 0 6 7 10];
y = 1:numel(x);
figure
plot(x, y, '.-')
grid
Probably the easiest way to sort the lines would be to look at the maximum values (x = 6.2E+4 or so), and then use those to define the preceding values. The maximum values are probably going to be at regular intervals in the vector, if all the lines are the same lengths, and in that instance, you can probably use the reshape function to break the single vector into different segments and then plot every segment in a different colour. if they are not, finding the indices of the maxima and using the mat2cell function could accomplish essentially the same thing.
Also, the ‘value’ entries do not make sense in the context of the plot. I would expect the Y-axis of the plot to begin at 1, instead it begins at 1158.
.
  댓글 수: 4
Jason
Jason 2024년 10월 16일
Awesome, thankyou!
Star Strider
Star Strider 2024년 10월 16일
A picture may be worth a thousand words, however actual data is worth a thousand pictures of it.
A represenetative sample of the data would work. Also, see if using the zip funciton to compress it in a .zip file would work. It might then meet the size requireements. (A .mat file could also work, although I am not certain if saving it to a .mat file would compress it to the required size.)
One option to find the ‘ends’ of each line could be to use the diff function.
I cannot work with data I do not have.
Simulating it —
x = [0:1000:62370 62340:-1000:0 0:1000:62400 flip([0:1000:62370 62340:-1000:0 0:1000:62400])].';
y = (1:numel(x)).';
xy = [x y];
LenX = numel(x);
iX = 1:LenX;
dx = gradient(x, iX); % Numerical Derivative
idx = dx > 0;
idxstart = [strfind([0; idx; 0].', [0 1]) LenX]; % Segment Start Indices
idxstop = strfind([0; idx; 0].', [1 0]); % Segment Stop Indices
SegLen = diff(sort([idxstart idxstop]));
SegLen(1) = SegLen(1)+1; % Segment Lengths (Corrected For ‘diff’)
figure
yyaxis left
plot(iX, x)
ylabel('x')
yyaxis right
plot(iX, dx)
hold on
plot(iX(dx>0), dx(dx>0), '.g')
plot(iX(dx<0), dx(dx<0), '.r')
hold off
ylabel('gradient(x)')
grid
xlabel('Index')
axis('padded')
title('Logic For Separating Segments')
figure
plot(x, y, '.-')
hold on
plot(x(idxstart), y(idxstart), 'sg', 'MarkerSize',10)
plot(x(idxstop), y(idxstop), 'sr', 'MarkerSize',10)
hold off
grid
xlabel('x')
ylabel('y')
title('Segments Defined')
xycell = mat2cell(xy, SegLen, size(xy,2)) % Separate Segments Into Individual Cells
xycell = 6x1 cell array
{64x2 double} {63x2 double} {63x2 double} {63x2 double} {63x2 double} {62x2 double}
figure % Plot The Segment Cells
hold on
for k = 1:numel(xycell)
plot(xycell{k}(:,1), xycell{k}(:,2), "DisplayName","Segment "+k)
end
hold off
grid
xlabel('x')
ylabel('y')
title('Plots Of Separate Segments')
legend('Location','best')
This is the best I can do without your actual data. You will likely have to adapt it.
.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Umar
Umar 2024년 10월 16일

Hi @Jason,

You asked, “I have a set of data (50k lines) representing a raster scan so there are several occurrances of the position zero (=X in my data). When I plot this, the whole plot is the same colour. I want to be able to change the colour once the x Pos changes direction (So everytime it reaches a zero, but there are sometimes 2 zeros)”.

After observing comments exchanged between you and @Star Star Strider, to achieve the desired effect of changing the plot color each time the x-position changes direction (especially at zero), I will focus on the relevant columns for x and y positions since data provided by you is large. Then, identify the points where the x-position changes direction which can be done by checking for zeros and determining the direction of change. Once the segments of data between direction changes is identified, you can plot each segment with a different color. Finally, plot the segments using the specified colors. Here is the complete code that implements the above steps:

% Sample Data (Replace this with your actual data)
data = [
  0 1159.681;
  30 1159.690;
  60 1159.700;
  90 1159.709;
  0 1160.000; % Direction change
  30 1160.986;
  60 1160.993;
  90 1160.999;
  0 1161.663; % Direction change
  30 1161.638;
  60 1161.614;
  90 1161.590;
];
% Extract x and y columns
xcol = 1;
ycol = 2;
X = data(:, xcol);
Y = data(:, ycol);
% Define colors for plotting
newcolors = [
  0.47 0.25 0.80; % Color 1
  0.83 0.14 0.14; % Color 2
  0.25 0.80 0.54; % Color 3
  1.00 0.54 0.00; % Color 4
  0.3960 0.5090 0.9920; % Color 5
  1 0 1; % Color 6
  0.2270 0.7840 0.1920; % Color 7
  1.0000 0.2700 0.2270; % Color 8
];
% Initialize figure
figure;
hold on;
% Find indices where x changes direction (i.e., where X is zero)
zeroIndices = find(X == 0);
segments = [1; zeroIndices; length(X) + 1]; % Include start and end
% Loop through segments and plot each with a different color
for i = 1:length(segments) - 1
  startIdx = segments(i);
  endIdx = segments(i + 1) - 1;
    if startIdx <= endIdx
        % Select color based on segment index
        colorIdx = mod(i - 1, size(newcolors, 1)) + 1; % Cycle through colors
        plot(X(startIdx:endIdx), Y(startIdx:endIdx), 'LineWidth', 2, 'Color', 
        newcolors(colorIdx, :));
    end
  end
% Finalize plot
grid on;
xlabel('X Position');
ylabel('Y Position');
title('Raster Scan Data with Direction Change Colors');
hold off;

Please see attached.

As you can see in the script above,sample data is defined in a matrix format. You should replace this with your actual data input method. Afterwards, set of colors is defined in an array. You can modify or expand this array as needed. The code identifies the indices where the x-position is zero, which indicates a change in direction, loops through each segment of data between the identified indices and plots them using different colors. The mod function is used to cycle through the defined colors. For more information on mod function, please refer to

https://www.mathworks.com/help/matlab/ref/double.mod.html

Finally, plot is finalized with grid lines, axis labels, and a title for clarity.

This approach will allow you to visualize your raster scan data, with clear indications of direction changes through color differentiation. You can further customize the colors and styles as per your requirements.

Hope this helps.

If you have any additional questions or need further modifications, feel free to ask!

카테고리

Help CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by