Combine multiple data series into a single series

15 ビュー (過去 30 日間)
Peter
Peter 2019 年 3 月 22 日
編集済み: Adam Danz 2020 年 8 月 19 日
Is there a way to combine multiple data series so that they only display as a single series in the Legend?
I have a function that uses 'plot' to plot multiple line segments. It can be thought of as a custom 'marker' shape class. Each data point is drawn using multiple line segments. I plot this (conceptually) single data series on the same plot as multiple other data series.
When I use the 'legend' function, each segment shows up as a separate element. So if I have plotted 2 series using the standard 'plot' function, and one using this custom function, with N data points, the legend thinks that there are N+2 data series. I want to treat this as 3 data series.

採用された回答

Adam Danz
Adam Danz 2019 年 3 月 22 日
編集済み: Adam Danz 2020 年 8 月 19 日
Specify a vector of object handles in your call to legend.
Example
hold on
h(1) = plot(x,y);
h(2) = plot(x2,y2);
h(3) = plot(x3,y3);
legend(h(1), 'data')
If you're using the 'DisplayName' property, you can use the legendUnq() FEX submission to represent only unique names in your legend.
Example
hold on
for i = 1:3
h(i) = plot(rand(1,10), rand(1,10, 'o'), 'DisplayName', sprintf('Data_%d',i));
end
legend(legendUnq(gca))
  2 件のコメント
Peter
Peter 2019 年 3 月 22 日
Thanks, this is exactly what I was looking for. I assumed that you could pass the handle into 'legend' but I couldn't figure out how.
I ended up outputing the handle of the first segment from the custom plot function.
hold on
h(1) = plot(x,y);
h(2) = plot(x2,y2);
h(3) = plotCustom(data);
Legend{1}='series 1';
Legend{2}='series 2';
Legend{3}='series 3';
legend(h,Legend)
function[h]=plotCustom(data)
...
h=plot([(xStart;xEnd],[yStart;yEnd],'color',c);
h=h(1);%combine all plotted segments into a single handle, so that the legend treats this as a single series
end
Adam Danz
Adam Danz 2019 年 3 月 22 日
編集済み: Adam Danz 2019 年 3 月 22 日
One simplification I could suggest: if you use the 'DisplayName' property in your call to plot, you don't need to produce the "Legend" cell array.
function[h]=plotCustom(data)
...
temph=plot([(xStart;xEnd],[yStart;yEnd],'color',c, 'DisplayName', sprintf('series %d', i))); % assumes 'i' is available
h(i)=temph(1);
...
legend(h)
end

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeVisual Exploration についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by