如何将文本标签(键)放在图例中线条的左侧?

vii*_*iiv 6 matlab gnuplot matlab-figure

我在很多地方进行了搜索,并没有找到一种方法来实现我想用MATLAB实现的目标:将键(文本标签)放在MATLAB图例中颜色线的左侧.

在此输入图像描述

我想实现这个结果,这是默认结果,例如使用gnuplot(参见上面的链接),显然可以使用MATLAB的堂兄Octave(参见Octave'slegend),可以选择这样做legend("left")"将[s]标签文本添加到钥匙的左边."

是否可以使用MATLAB完成?

Sue*_*ver 7

使用legend@ nirvana-msu提到的第二个输出略微更新.

我们可以通过检索它们的当前位置并改变它来调整图例中的文本和绘图对象的位置.图例中所有项目的位置单位是0到1之间的标准化数据单位.

像下面这样的东西应该工作.

%// Create some random data and display
figure;
p = plot(rand(2,3));
[L, handles] = legend({'one', 'two', 'three'});

%// Get the text handles
texts = findall(handles, 'type', 'text');

%// Get the line handles
lines = findall(handles, 'type', 'line');

%// Get the XData of all the lines
poslines = get(lines, 'XData');

%// Subtract 1 from all the positions and take the absolute value
%// this will shift them to the other side as the xlims are [0 1]
set(lines, {'XData'}, cellfun(@(x)abs(x - 1), poslines, 'uni', 0))

%// Get the position of all of the text labels
postext = get(texts, 'Position');

%// Figure out where the lines ended up
xd = get(lines, 'xdata');
xd = cat(2, xd{:});

%// Have the labels be next to the line (with 0.05 padding)
positions = cellfun(@(x)[min(xd) - 0.05, x(2:3)], postext, 'uni', 0);
set(texts, {'Position'}, positions, ...
           'HorizontalAlignment', 'right');
Run Code Online (Sandbox Code Playgroud)

R2014a

在此输入图像描述

R2015b

在此输入图像描述


nir*_*msu 5

这是一个适用于HG1和HG2的解决方案.

这个想法有点类似于@Suever的答案 - 我们想要翻转图例中的所有文字,线条和标记,但是有一些显着的差异:

  1. 没有必要搜索linetext处理使用findall- 它们可用作legend功能的第二个输出.
  2. 没有必要猜测合理的位置应该是什么.我们只需要对称地翻转所有控件.通过线条,您可以轻松XData获得起点和终点.有了文本,因为你需要控制Position,即左边缘,但是你需要知道文本宽度来计算对称变换,这有点棘手.Extent财产给了我们我们所缺少的东西.

码:

hFig = figure();
axh = axes('Parent', hFig);
plot(axh, randn(100,2), '-*');
[~, hObjs] = legend(axh, {'first','second-some-long-text'});

for i = 1:length(hObjs)
    hdl = hObjs(i);
    if strcmp(get(hdl, 'Type'), 'text')
        pos = get(hdl, 'Position');
        extent = get(hdl, 'Extent');    % we need text x-position and width
        pos(1) = 1-extent(1)-extent(3); % symmetrical relative to center
        set(hdl, 'Position', pos);
    else     % 'line'
        xData = get(hdl, 'XData');
        if length(xData) == 2 % line
            xDataNew = [1-xData(2), 1-xData(1)];
        else % length(xData)==1, i.e. marker
            xDataNew = 1-xData;
        end
        set(hdl, 'XData', xDataNew);
    end
end
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述