首页 文章

matlab - 在原点设置刻度标签

提问于
浏览
2

在使用Matlab生成绘图时,当x和y最小值都为零时,我更喜欢只有一个零标记原点而不是在两个轴上表示它 .

Matlab默认为后者,就像这样

figure with 'double origin'

而我想要更像这样的东西

figure with 'single origin'

这可以手动完成,但我正在尝试自动化该过程 . 删除 0xy 刻度标签显然很容易 . 但是,我可以't seem to access any handle for the position of the axis tick labels to properly position a text box for the '知道这是否是所有图形或轴的标准 .

有任何想法吗?

我正在运行Matlab 2014b .

2 回答

  • 0

    这是一个简单的方法:

    % somthing to plot:
    x = 0:0.1:2*pi;
    y = abs(sin(x)+cos(x));
    plot(x,y)
    
    % get the handle for the current axes:
    ax = gca;
    % get the position of the zero tick on y-axis:
    zeroYtick = ax.YAxis.TickValues==0;
    % remove it (tick and lable)
    ax.YAxis.TickValues(zeroYtick) = [];
    

    结果:

    zero tick

    如果您希望 0 向左偏移一点,那么它将位于绘图的角落,您可以使用注释:

    % get the position of the zero tick on x-axis:
    zeroXtick = ax.XAxis.TickValues==0;
    % remove it (tick and lable)
    ax.XAxis.TickValues(zeroXtick) = [];
    % place a new zero at the origin:
    dim = [0.1 0.01 0.1 0.1];
    annotation('textbox',dim,'String','0',...
        'FitBoxToText','on','LineStyle','none')
    

    你会得到:

    zero tick 2

    annotation的优势在于原点始终相对于轴的角落放置,并且您无需知道轴刻度值以正确偏移它 .


    EDIT:

    对于2016年前版本,您可以使用以下内容(我写得更紧凑):

    ax = gca;
    % remove the zero tick on y-axis (tick and lable):
    ax.YTick(ax.YTick==0) = [];
    % remove the zero tick on x-axis (tick and lable):
    ax.XTick(ax.XTick==0) = [];
    % place a new zero at the origin:
    dim = [0.1 0.01 0.1 0.1];
    annotation('textbox',dim,'String','0',...
        'FitBoxToText','on','LineStyle','none')
    

    EDIT 2:

    保持 0 到位的另一个选择是将它粘在轴上 . 这是通过用轴手柄替换 Parent 来完成的 . 首先,我们需要一个注释句柄(从上一次编辑继续):

    t = annotation('textbox',dim,'String','0',...
        'FitBoxToText','on','LineStyle','none');
    

    然后我们切换 Parent 并设置新位置:

    t.Parent = ax;
    t.Position(1:2) = -[0.2 0.1];
    

    最后,我们通过将 Units 转换为像素来超级粘合它:

    t.Units = 'Pixels';
    
  • 0

    以下内容将排除y轴上的第一个刻度,而不会移动图形 . 您可以通过在移除第一个轴限制之前设置轴限制,或者手动设置yTicks, set(h,'yTick',my_ticks) 来确保删除正确的项目 . 请注意 yTick 会更改刻度线的位置,而 yTickLabel 将更改 yTick 每个位置出现的文本

    h = plot([0,1],[0,1]);
    yTicks = get(h,'yTick');
    set(h,'yTick',yTick(2:end));
    

相关问题