获取XTick位置并在其附近显示文本

时间:2017-01-11 20:56:30

标签: matlab plot matlab-figure

我的目标:使用text命令将文字放在xtick附近,但不是通过 xticklabel

示例: 假设我有以下代码

figure
plot([1:10],[1:10])
set(gca, 'XTick',[3])
set(gca, 'XTickLabel',{''})

现在,我想写一些类似的东西(这不是一个有效的代码)

ticklocs = get(gca,'xtick',locations);
text(locations(1),locations(2), 'my cool text here');

我知道我可以将文字放在XTickLabel格式中,但它无法使我text允许我的所有文字灵活性。

如果您知道如何将Latex放入xticklabel,这也很有意思,但这个帖子的主题(只是评论)。

1 个答案:

答案 0 :(得分:1)

您可以获得xtick属性,该属性将为您提供刻度线的x值。然后,您可以使用轴ylim属性来确定最小y值,这将是它的粗略y位置。然后,您可以根据需要对这些值应用填充,并使用text在任何地方显示文本。

ax = axes();

% Get the upper and lower y limits
ylims = get(ax, 'ylim');

% Get the x positions of the tick marks
xticks = get(ax, 'xtick');

% For each tick we're going to use padding between -10% of the ylimits to 10%
padding = linspace(-0.1, 0.1, numel(xticks));

for k = 1:numel(padding)
    % Compute the y value based upon the desired padding and the lower y limit
    yvalue = ylims(1) - diff(ylims) * padding(k);

    % Display the text
    text(xticks(k), yvalue, sprintf('Label %d', k), 'HorizontalAlignment', 'center');
    hold on
end

enter image description here

话虽如此,自R2015a起,您可以将LaTeX直接放在xtick标签中,并使用axes的{​​{3}}属性来指定您想要使用LaTeX解释器。

axes('Xtick', [0 0.5 1], ...
     'XTickLabel', {'10\circ', 'x^{1}', 'Y_2'}, ...
     'TickLabelInterpreter', 'latex')

TickLabelInterpreter