Different Colors in plot and legend
이전 댓글 표시
Hi,
In an app I am working on, I am plotting different graphs toghether in one plot. The first 6 lines need defined colors, the rest does not. This part is working correctly, but the legend shows the same color for the other graphs as the graphs before and not the actual colors. Does it have something to do with the arrays for the first six lines? I tried initializing them as 1x500 and 500x1 arrays but that didn't make a difference. Unfortunately, I also can't "hardcode" the legend using 'DisplayName' when plotting, as the number of plots can be different. The code I provided is a bit downsized for readability and I only cut out parts that either don't run in this case (ifs and switches) or just change the label or name of the graphic or figure.
Any guesses?

figure()
hold on
app.Data = getAllCycles(app);
x = linspace(0, app.CycleToEvaluateSlider.Limits(2), 500);
dataType = strcat(dataType, "(A)");
% linearly distributed values from 0 to the limit of the slider (number of cycles)
% number of values = rows in target sheet
y = zeros(500,1)+targets.(dataType)(1);
plot(x,y, 'r')
if strcmp(dataType,"temp")
y = zeros(500,1)+targets.(dataType)(2);
plot(x,y, 'Color', [1 0.64 0.57])
y = zeros(500,1)+targets.(dataType)(3);
plot(x,y, 'Color', [1 0.64 0.57])
strLegend = ["Target", "Min", "Max",app.DataToInclude.Items];
else
y = zeros(500,1)+targets.(dataType)(2);
plot(x,y, 'r')
for i=3:1:length(targets.(dataType))
y = zeros(500,1)+targets.(dataType)(i);
plot(x,y, 'Color', [1 0.64 0.57])
end
strLegend = ["Min", "Max", "MinTol-", "MinTol+", "MaxTol-",...
"MaxTol+",app.DataToInclude.Items];
end
for i=2:2:size(app.Data,2)
x = app.Data.(i-1);
y = app.Data.(i);
plot(x,y)
end
xlabel("Period number")
ylabel('Force in N')
set(gcf,'Name', strjoin([app.TesttypeDropDown.Value ", " app.DatatypeDropDown.Value]))
legend(strLegend, 'Interpreter', 'none');
set(gca,"Fontsize", 20)
set(gca,"fontname", "Arial")
set([gca, gcf], 'units', 'centimeters')
set(gca, 'Position', [3 2 26 17]) %position and size of the chart
set(gcf, 'Position', [0 2 30 20]) %position and size of the figure (window)
set(gca,'XMinorTick','on','YMinorTick','on')
set(gca,'YGrid','on')
hold off
댓글 수: 2
Rik
2023년 4월 24일
I always try to use DisplayName. That way it is immediately obvious when you're creating multiple line objects when you intend to only create one. I suspect that is the case here as well.
You should also consider creating an array of handles to feed into legend. That way you also have more control over what is happening, and it makes it easier to spot when you have more objects than you expected.
Moritz
2023년 4월 25일
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Creating, Deleting, and Querying Graphics Objects에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
