【问题标题】:Changing the legend of a figure so that various lines share the same legend entry更改图例的图例,使各行共享相同的图例条目
【发布时间】:2019-06-05 07:24:31
【问题描述】:

一位同事向我传递了一个.fig 文件,该文件在同一个图上有许多行,并且根据它们所属的组进行着色。下图供参考。

我需要更改图例,以便相同颜色的线条具有相同的图例条目。问题是我无法访问原始数据,所以我不能使用提到的方法here 所以有没有办法只使用.fig 文件来更改图例条目?我尝试在属性检查器中将一些图例名称更改为NaN,但这只是将条目更改为 NaN。

【问题讨论】:

    标签: matlab matlab-figure


    【解决方案1】:

    如果您有 *.fig 文件,如果您了解 MATLAB Graphics Objects Hierarchy,则可以使用“get”方法提取任何包含的数据。

    例如,请参阅下面的左图作为您的 *.fig 文件的示例。您可以通过挖掘当前图形对象的Children 来提取其中的数据。

    % Open your figure
    fig = openfig('your_figure.fig');
    % fig = gcf     % If you have the figure already opened
    title('loaded figure')
    
    % Get all objects from figure (i.e. legend and axis handle)
    Objs = get(fig, 'Children');      
    % axis handle is second entry of figure children
    HA = Objs(2);          
    % get line objects from axis (is fetched in reverse order)
    HL = flipud(get(HA, 'Children'));     
    
    % retrieve data from line objects
    for i = 1:length(HL)
        xData(i,:) = get(HL(i), 'XData');
        yData(i,:) = get(HL(i), 'YData');
        cData{i} = get(HL(i), 'Color');
    end
    

    现在将图中所有行的xy数据提取到xDatayData。颜色信息保存到单元格cData。您现在可以按照您想要的方式重新绘制带有图例的图形(例如,使用您已经找到的 SO 解决方案):

    % Draw new figure with data extracted from old figure
    figure()
    title('figure with reworked legend')
    hold on
    for i = 1:length(HL)
        h(i) = plot(xData(i,:), yData(i,:), 'Color', cData{i});
    end
    
    % Use method of the SO answer you found already to combine equally colored
    % line objects to the same color
    legend([h(1), h(3)], 'y1', 'y2+3')
    

    结果是右下图,每种颜色只列出一次。

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 2014-07-07
      相关资源
      最近更新 更多