Plotting color data from cell array using plot()

조회 수: 15 (최근 30일)
Sam
Sam 2025년 5월 30일
답변: Walter Roberson 2025년 5월 30일
I want to quickly plot several hundred traces quickly Using a for loop tends to take quite some time. I found a trick to do it using the following example,
x1 = [1 2 3]
x2 = [2 3 4]
y1 = [1 2 3]
y2 = [3 5 6]
xdata = {x1 x2}
ydata = {y1 y2}
plot(xdata{:}, ydata{:})
BUT
what if i want to color code the data in a specific way? I tried the following, but it doesnt work.
x1 = [1 2 3]
x2 = [2 3 4]
y1 = [1 2 3]
y2 = [3 5 6]
c1 = [1 0 1]
c2 = [0 1 0]
xdata = {x1 x2}
ydata = {y1 y2}
cdata = {c1 c2}
plot(xdata{:}, ydata{:}, 'color', cdata{:})
Is there any way to assign additional information to the information being plotted using plot() such as color, or line style? If not, is there another function? Or must a for loop be used for this

채택된 답변

Walter Roberson
Walter Roberson 2025년 5월 30일
plot(xdata{:}, ydata{:})
is equivalent of
plot(xdata{1}, xdata{2}, ydata{1}, ydata{2})
which is going to treat the data as pairs and plot xdata{1} against xdata{2}, and plot ydata{1} against ydata{2}
To do it right you would need something like
xydata = [xdata; ydata];
plot(xydata{:})
Also
plot(xdata{:}, ydata{:}, 'color', cdata{:})
Would be treated as
plot(xdata{1}, xdata{2}, ydata{1}, ydata{2}, 'color', cdata{1}, cdata{2})
which would fail because cdata{2} is not the name of a valid named option.
Is there any way to assign additional information to the information being plotted using plot() such as color, or line style?
No. For any one plot() call, if you specify multiple name/value pairs with the same name, then it is the last pair that is used.
Although you could construct
cdata = [cellstr(repmat('color', length(xdata), 1)), {c1; c2}];
plot(xydata{:}, cdata{:})
to get the effect of
plot(xdata{1}, xdata{2}, ydata{1}, ydata{2}, 'color', c1, 'color', c2)
because of the rules around last-processed option, this would be equivalent to
plot(xdata{1}, xdata{2}, ydata{1}, ydata{2}, 'color', c2)
and the c1 color information would be ignored.
What you can do is
h = plot(xydata{:});
cdata = {c1 c2};
set(h, {'color'}, cdata(:))
This takes advantage of a special syntax of set(), that if you provide a cell array of a property name, then the property name will be effectively duplicated once for each handle and the corresponding cdata value will be used

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

태그

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by