gpt4 book ai didi

matlab 奇数 xtick/ytick 标签行为

转载 作者:行者123 更新时间:2023-12-04 11:58:36 24 4
gpt4 key购买 nike

我偶然发现了 matlab 的 xticklabels 和 yticklabels 行为的不直观行为。我将 xticklabels 的输出存储到一个变量中,修改它,然后再次应用它并注意标签现在已经移动了。这是预期的行为,如果是,为什么(可选:为什么将其作为预期行为有意义)?
想法:为每一步显示 xticks,但只为每第二步显示标签。

%setup a figure to display
figure;
data=randn(1,21);
plot(-10:10,data);
xlim([-5 10]) %cut out a piece of interest from the data
xticks(-10:2:10); %adjust tick spacing to favorite

%now: keep xticks but remove every 2nd label
lbls=xticklabels;
lbls(1:2:end)={' '}; %set every 2nd label to empty space
pause(1); %take a deep breath...
xticklabels(lbls)
enter image description here
enter image description here

最佳答案

问题是,虽然xtick函数返回所有现有刻度(可见和隐藏的)的值,xticklabels函数只返回可见刻度的标签。我想这种行为是由于 MATLAB 没有为不可见的刻度分配任何标签。
因此,您的 xtick 向量是:

[-10 -8 -6 -4 -2 0 2 4 6 8 10]
虽然您的 xticklabels 元胞数组是:
{'-4'}, {'-2'}, {'0'}, {'2'}, {'4'}, {'6'}, {'8'}, {'10'}
并且,更换后:
{' '}, {'-2'}, {' '}, {'2'}, {' '}, {'6'}, {' '}, {'10'}
由于图片中唯一可见的刻度是分配给范围从 -4 到 10 的刻度,因此相应的显示标签是元胞数组中从第四个到最后一个的元素。没有分配标签的刻度(因为标签少于刻度)以空单元格为特征:
{'2'}, {' '}, {'6'}, {' '}, {'10'}, {empty}, {empty}, {empty}
解决方案:
您有多种解决方案。第一个是删除不在 x 轴范围内的刻度:
%setup a figure to display
figure;
data=randn(1,21);
plot(-10:10,data);
xlim([-5 10]) %cut out a piece of interest from the data
xticks(-10:2:10); %adjust tick spacing to favorite

% Delete external ticks
xt = xticks();
xl = xlim(); xt(xt<xl(1)) = []; xt(xt>xl(2)) = []; xticks(xt);

%now: keep xticks but remove every 2nd label
lbls=xticklabels;
lbls(1:2:end)={' '}; %set every 2nd label to empty space
pause(1); %take a deep breath...
xticklabels(lbls)
Result(1)
另一种解决方案是手动分配标签,将 xticks 返回的数字转换为字符串值:
%setup a figure to display
figure;
data=randn(1,21);
plot(-10:10,data);
xlim([-5 10]) %cut out a piece of interest from the data
xticks(-10:2:10); %adjust tick spacing to favorite

%now: keep xticks but remove every 2nd label
lbls= arrayfun(@(x) num2str(x), xticks(), 'UniformOutput', false);
lbls(1:2:end)={' '}; %set every 2nd label to empty space
pause(1); %take a deep breath...
xticklabels(lbls)
Result(2)
您会注意到两种解决方案之间的刻度不同。这是由于两个向量之间的偶数/奇数元素不同,因此不同的元素被替换为空白。

关于matlab 奇数 xtick/ytick 标签行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67033656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com