如何在Matlab中最佳设置日期轴

时间:2018-12-11 15:29:01

标签: matlab matlab-figure axis axis-labels

您能帮我在Matlab中设置日期轴还是将我指向正确的帖子?

我的问题如下: 我有一些要绘制的数字格式的价格和日期,例如:

 Prices = repmat([10; 5; 3; 4; 11; 12; 5; 2],10,1);

 Dates = [726834:726834+8*10-1]';

如果我这样绘制它们:

 plot(Dates,Prices)
 dateaxis('x',17)

我得到了我不想要的x轴值,因为它们看起来不规则(我猜它们遵循某些规则,但看起来不太好)。我如何最好地将它们设置为例如始终是每月的第一天,一月的第一天和七月的第一天等等?我知道我可能可以使用set(gca,'xtick',???????);但是我对如何完全做到这一点缺乏概述,而Matlab的帮助也无济于事。

1 个答案:

答案 0 :(得分:2)

此代码在每个月的第一天标记该图。要获取每年的一月或七月,应该只选择month数组的某些元素。该策略是使用eomdate来获取每月的最后一天并加1。图1为您提供每月的第一天,而图2为您提供了在months_to_display数组中选择的月份。

Prices = repmat([10; 5; 3; 4; 11; 12; 5; 2],10,1);

Dates = [726834:726834+8*10-1]';

firstDate = strsplit(datestr(Dates(1)-1, 'dd,mm,yyyy'),',');
lastDate = strsplit(datestr(Dates(end), 'dd,mm,yyyy'),',');

months = mod(str2double(firstDate{2}):str2double(lastDate{2})+12*(str2double(lastDate{3})-str2double(firstDate{3})),12);
months(months == 0) = 12;

years = zeros(1,length(months));
currYear = str2double(firstDate{3});
for i = 1:length(months)
    years(i) = currYear;
    if (months(i) == 12)
        currYear = currYear + 1;
    end
end

dayCount = eomdate(years,months);
firstDates = dayCount+1;

figure(1)
plot(Dates, Prices)
xticks(firstDates);
xticklabels(datestr(firstDates));

months_to_display = [1 7];
months_to_display = months_to_display - 1;
months_to_display(months_to_display == 0) = 12;
months_to_collect = ismember(months, months_to_display);

months = months(months_to_collect);
years = years(months_to_collect);

dayCount = eomdate(years,months);
firstDates = dayCount+1;

figure(2)
plot(Dates, Prices)
xticks(firstDates);
xticklabels(datestr(firstDates));