如何减少matlab中的图例宽度

时间:2015-02-25 01:04:09

标签: matlab

我正在使用matlab绘制一些项目数据,看看打击数字。现在我正在尝试剪切图例宽度,以使线条看起来不那么宽。我按照Benoit_11的建议尝试了这些命令:

[~,icons,~,~] = legend(leg,'location','northwest');
hline = icons(2);
linedata = get(hline,'xdata');
newdata = [linedata(1)+0.2 linedata(2)];
set(hline,'xdata',newdata,'linewidth',1)

我正在使用for循环来绘制这些数字,因为我有多个数据可以同时进行分析。现在我可以立即改变图例线的长度。但是我遇到了另一个问题:如果我有不同长度的图例文本,即使我设置了相同的起点和终点,我最终会得到不同的长度(你可以从图中看到)。我试图修改icon(1)但总是得到错误。有什么建议? enter image description here

2 个答案:

答案 0 :(得分:3)

有两件事情你的代码没有做得正确(除了你使用size作为传奇句柄的事实......因为size是一个风险因素内置功能):

1)仅使用1个参数调用legend会返回图例对象的句柄,并且获取其位置实际上会为您提供包围图例的框的位置,即文本+行。

2)使用这一行:

p(3) = p(3) - 0.06;

确实会修改位置,但您需要设置图例的新位置,如下所示,以使更改生效:

set(HandleToLegend,'Position',p)

回到你的问题,诀窍是在调用legend期间分配许多输出;然后,您可以修改图例对象的特定元素。

实际上我们只需要4个输出参数中的1个,在文档中称为icons,所以我会坚持使用符号。然后,我们可以获取该行的XData属性并根据需要进行修改。 XData实际上是一个2元素的向量:

[StartingPoint EndingPoint]

因此,更改其中一个(或两者)将更改图例框中显示的行的长度。

这是带注释的整个代码;我更改了第二个图中线条的长度和线宽,以突出显示更改。

clear
clc
close all
x = 1:10;
y = rand(1,10);
figure;

%// Default case
subplot(1,2,1)
plot(x,y);

legend('First plot','Location','NorthWest');

title('Before','FontSize',18);

%// With modifications
subplot(1,2,2)
plot(x,y);
title('After','FontSize',18);

%//========================
%// Change the legend here
%//========================

%// The "icons" output is what you want
[~,icons,~,~] = legend('First plot','Location','NorthWest');

%// icons(1) is the text of the current element in the legend Here its 'First plot'
i_1 = get(icons(1)); %// access the properties with this command.

%// icons(2) is the line associated with that text. Here the blue line.
i_2 = get(icons(2));

%// Mhh I don't know what icons(3) represents haha sorry about that.
i_3 = get(icons(3));


%// Get the actual line
hline = icons(2);

%// Fetch its XData property
LineData = get(hline,'XData')

%// Play with those 2 elements to see the output change.
NewData = [LineData(1)+.2 LineData(2)-.01];

%// Apply the changes
set(hline,'XData',NewData,'LineWidth',3)

其中包含以下内容:

enter image description here

答案 1 :(得分:-1)

您需要设置Position属性的值,您只需更改向量p即可。 p根本不影响情节,它只是一个数字向量。您必须修改它,然后使用

将其应用回绘图
set(size,'Position',p)

然而,传奇似乎确实存在最小宽度。

相关问题