【问题标题】:How to add an independent text in MATLAB plot legend如何在 MATLAB 绘图图例中添加独立文本
【发布时间】:2017-06-07 20:20:48
【问题描述】:

我需要在图例中添加与图形数据无关的附加文本以及图例标题。 像这样的东西(它是在 OriginLab 制作的):

按照这个链接Add custom legend without any relation to the graph 我可以使用plot(NaN,NaN,'display','add info here2', 'linestyle', 'none') 添加一些文本。但是这段文字有一个缩进:

如何避免这种缩进?还有没有更优雅的方法将与图例无关的文本与图例标题一起添加?

【问题讨论】:

  • 并不是说它是最好的解决方案,但也许你会发现它有用:legtools

标签: matlab plot matlab-figure


【解决方案1】:

我认为最简单的方法是创建一些虚拟函数,绘制它但设置 color="none" - 这样它只会显示在图例中(如果这是你想要的)。

【讨论】:

    【解决方案2】:

    legend 函数将返回组成图例中的符号和文本的所有组件的第二个输出参数句柄。因此,您可以将“虚拟”行绘制为图例中的占位符,在创建图例时重新排序句柄以将文本放置在您想要的位置,并相应地修改图例对象。这是一个例子:

    x = linspace(0, 2*pi, 100);
    hl = plot(x, [sin(x); cos(x); tan(x); nan(size(x))].');          % Add a line of NaNs
    axis([0 2*pi -4 4]);
    [~, objH] = legend(hl([1 2 4 3]), 'sin', 'cos', 'junk', 'tan');  % Reorder handles
    set(findobj(objH, 'Tag', 'junk'), 'Vis', 'off');           % Make "junk" lines invisible
    pos = get(objH(3), 'Pos');                                 % Get text box position
    set(objH(3), 'Pos', [0.1 pos(2:3)], 'String', 'also...');  % Stretch box and change text
    

    【讨论】:

    • 感谢您的回答。看起来我需要。
    【解决方案3】:

    您可以使用注释。它并不完美,但只需稍作调整,您就会得到您想要的。这是一个例子:

    % somthing to plot:
    x = [0:0.1:5; 5:0.1:10].';
    y = sin(x);
    % plot the real data:
    plot(x,y);
    hold on
    % make some space in the legend:
    Spacing_lines = 3;
    h = plot(nan(size(x,1),Spacing_lines));
    hold off
    set(h,{'Color'},{'w'}); % clear the dummy lines
    % place the legend:
    hl = legend([{'lable1','lable2'} repmat({''},1,Spacing_lines)]);
    % add your text:
    annotation('textbox',hl.Position,'String',{'Some info';'in 2 lines'},...
        'VerticalAlignment','Bottom','Edgecolor','none');
    

    从这里你得到:

    【讨论】:

    • 感谢您的回答。不幸的是,“gnovice”的解决方案更好。
    • @AlexanderKorovin 我同意 :)
    【解决方案4】:

    您可以通过这种方式将任何文本添加到任何情节点:

    txt1 = 'some information';
    text(x1,y1,txt1)
    

    x1, y1 在哪里 - 坐标。

    顺便说一句,函数text 函数有很多不同的属性(颜色、字体大小、对齐方式等)。

    【讨论】:

    • 感谢您的回答。但这不是一个好的解决方案。在这种情况下,我必须调整带有图例的文本。另外,如果我想在两条曲线的描述之间放置文本,还有一个问题,如我的问题所示。我当然可以自己创造一个图例(但我必须知道我的曲线的颜色、线条样式和符号。所以这是一项艰苦的工作)。
    猜你喜欢
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    相关资源
    最近更新 更多