首页 文章

Matlab 2014b勾选标记之间的标签

提问于
浏览
2

我正在Matlab 2014b中创建一个条形图,并希望将x轴标签置于刻度标记之间 . 例如,在下图中,使用 datetick 按年度正确分割条形,并进行稍微调整 . 但是,我希望标签出现在当前指定的刻度线之间的中间位置 .

clear; close all;
a = rand(12, 1)-0.1;
x = linspace(datenum('03-31-2012'), datenum('12-31-2014'), 12);
b1 = bar(x, a);
datetick('x', 'yyyy');
display(datestr(x))

ax1 = gca;
bGapWidth = (x(2)-x(1));
bWidth = b1.BarWidth;

ax1.XLim = [x(1)-bGapWidth*bWidth x(end)+bGapWidth*bWidth];

initTick = ax1.XTick;
ax1.XTick = initTick + (bWidth*bGapWidth)/2 + (bGapWidth*(1-bWidth)/2);

我见过a few类似的问题,但没有完全相同 . 我也看到suggestions创建了一个虚拟轴(一个用于标签,一个用于刻度线),但我也遇到了一些麻烦 - 只需将一个新变量设置为等于当前轴对象并进行修改即可更改整个绘图 . 请随意帮助我解决这个问题,或建议更好的解决方案 .

1 回答

  • 1
    clear; close all;
    a = rand(12, 1)-0.1;
    x = linspace(datenum('03-31-2012'), datenum('12-31-2014'), 12);
    b1 = bar(x, a);
    datetick('x', 'yyyy');
    display(datestr(x))
    
    h1=get(gca,'XTick');
    h2=get(gca,'XTickLabel');
    h3=length(h1);
    xdiff=h1(2)-h1(1); % assuming uniform step interval in x-axis
    h1=h1+0.4*xdiff; % this factor of 0.4 can be adjusted
    ylim([0 1]);
    for i=1:h3-1
        text(h1(i),-0.05,num2str(h2(i,:))); 
    end
    % instead of -0.05 relative to y put the labels where you like
    set(gca,'XTickLabel',{});
    

    enter image description here

相关问题