【问题标题】:How to add legend in a highlighted graph?如何在突出显示的图表中添加图例?
【发布时间】:2017-11-12 02:33:53
【问题描述】:

我想根据不同的高亮边在图 G 中添加图例。只用一张图G可以做到吗?

这是一个可以玩的玩具示例。我有一个情节G

adj =[0 0 1 1 1;   % adjacency matrix
      1 0 1 0 1;
      0 1 0 1 1;
      1 1 1 0 1;
      0 0 1 0 0]
G = digraph(adj);

我根据边缘类型用 3 种颜色突出显示所有边缘。 3 种类型的边表明在我的情况下节点之间有 3 种不同的关系。

这就是我突出显示所有边缘的方式:

M(:,:,1)=[0 0 1 0 0;1 0 0 0 1;0 0 0 0 0;1 0 0 0 0;0 0 1 0 0];
M(:,:,2)=[0 0 0 1 0; 0 0 1 0 0;0 1 0 0 1;0 0 0 0 0;0 0 0 0 0];              
M(:,:,3)=[0 0 0 0 1; 0 0 0 0 0; 0 0 0 1 0;0 1 1 0 1;0 0 0 0 0];

我的问题的困难在于我必须删除出度小于某个整数的顶点(比如 2)。因此我不能独立绘制 3 个图。

rmvNode=find(outdegree(G)<2);    % outdegree is the reason why single G is neccesary
adj(rmvNode,:)=[]; adj(:,rmvNode)=[];
M(:,rmvNode,:)=[]; M(rmvNode,:,:)=[];
G=digraph(adj);

然后我们可以绘制它。

for k=1:3           %Looping depending on the third dimension
    [r,c]= find(M(:,:,k));  %Finding non-zero elements
    s{k}=r;     t{k}=c;    
end
h=plot(G);
highlight(h,s{1},t{1},'EdgeColor','r');
highlight(h,s{2},t{2},'EdgeColor','g');
highlight(h,s{3},t{3},'EdgeColor','b');

我的理想情况是这样的图例:将红色边缘分配给标签'type 1',将蓝色边缘分配给'type 2',并将绿色边缘分配给'type 3'。我想要这样的东西:

再一次:我不能根据 M 中的 3 页独立绘制 3 个图形,将 3 个图形组合在一起,然后添加一个图例。因为如您所见,outdegree 需要整个图 G 作为输入,所以将G 划分为G1G2G3 是不可行的。

【问题讨论】:

  • 您可以为此目的使用annotation
  • btw 从您的代码的这些行中,highlight(h,s{2},t{2},'EdgeColor','g');highlight(h,s{3},t{3},'EdgeColor','b');看来您希望类型 2 为绿色,类型 3 为蓝色(我在回答中遵循了这一点)但在粗略的人物,你交换了这些颜色。
  • @SardarUsama 感谢您指出这一点以及隐形情节的想法。太棒了!
  • 不客气!

标签: matlab plot graph matlab-figure legend


【解决方案1】:

一种方法是通过添加一个不可见的plot 来操纵legend 函数,如下所示:

%put this at the end of your code
hold on;                                      %to retain current plot
ax=plot(NaN,NaN,'r',NaN,NaN,'g',NaN,NaN,'b'); %plotting invisible points of desired colors
legend(ax,'Type 1','Type 2','Type 3');        %adding the legend

给出:

【讨论】:

  • 最好使用nans 作为你的虚拟数据,因为它们是真正不可见的。
猜你喜欢
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多