Search code examples
matlabdatetimeplotresolutiontemporal

datetime matlab different temporal resolution


I am trying to plot two timeseries in one graph. Unfortunatelly, the data sets have different temporal resolutions and my code using datetime does not work. My aim is one xtick per hour. Any idea how I can solve that problem? Thanks!

dataset1 = rand(1,230).';
dataset2 = rand(1,33).';

xstart = datenum('19/02 09:00','dd/mm HH:MM');
xend = datenum('21/02 18:00','dd/mm HH:MM');
x = linspace(xstart,xend,20);
Dat = linspace(xstart,xend,numel(dataset1));
x1=[1:1:230].' %values every 15 minutes


x0_OM = datenum('19/02 09:00','dd/mm HH:MM');
x1_OM = datenum('20/02 18:00','dd/mm HH:MM');
xData = linspace(x0_OM,x1_OM,20);
Dat2 = linspace(xstart,xend,numel(dataset2));
x2=[1:4:130].' %hourly values


fig=figure ();

yyaxis left
plot(x1,dataset1);
ylabel('Dataset 1')
xlabel('timesteps (15min Interval)');
yyaxis right
plot(x2,dataset2);
ylabel('Dataset 2')
set(gca,'XTick', xData) %does not work
datetick('x', 'dd/mm HH:MM', 'keeplimits','keepticks') %does not work

Solution

  • I generalized your code a bit and used something nicer to inspect than random numbers. I removed the labelling part to keep the script short.

    % Dataset 1, 15 minutes interval
    xstart1 = datenum('19/02 09:00','dd/mm HH:MM');
    xend1 = datenum('21/02 18:00','dd/mm HH:MM');
    Dat1 = xstart1:1/24/4:xend1;                           % 1/24/4 is a 15 minutes step
    dataset1 = sin(linspace(0, 2*pi, numel(Dat1)));
    
    % Dataset 2, 1 hour interval
    xstart2 = datenum('19/02 09:00', 'dd/mm HH:MM');
    xend2 = datenum('20/02 18:00', 'dd/mm HH:MM');
    Dat2 = xstart2:1/24:xend2;                             % 1/24 is a 1 hour step 
    dataset2 = cos(linspace(0, 2*pi, numel(Dat2)));
    
    % Determine "global" start and end.
    xstart = min(xstart1, xstart2);
    xend = max(xend1, xend2);
    Dat = xstart:1/24:xend;
    
    % Plot
    fig = figure();
    hold on;
    plot(Dat1, dataset1, '*');
    plot(Dat2, dataset2, 'r*');
    set(gca, 'XTick', Dat);
    datetick('x', 'dd/mm HH:MM', 'keepticks', 'keeplimits');
    hold off;
    

    Principally, that should work, but the output is not nice, due to the long tick labels. Could you please check, if that is, what you wanted to achieve?