Create and Plot Time Series Data in Matlab - matlab

I have a (1x700) vector x for which I would like to create and plot a time series object in Matlab. Each observation corresponds to one month, and the first observation belongs to January 1960. I tried the following:
state1 = timeseries(x,1:size(x,2));
state1.Name = 'Test';
state1.TimeInfo.Units = 'months';
state1.TimeInfo.StartDate = 'Jan-1960'; % Set start date.
state1.TimeInfo.Format = 'yy'; % Set format for display on x-axis.
state1.Time = state1.time - state1.time(1); % Express time relative to the start date.
plot(state1);
However, I still see numbers on the x-axis instead of years. Could anyone please help? Thanks in advance!

Create random data. 1/12 corresponds to the fraction of a year that each month represents.
x = 1960:1/12:1970;
y = rand(1,121);
Then plot the x and y axes data using plot.
plot( x, y )
Then set the tick as follows for a decade per year. 1960:1970 will generate [1960 1961 ...] each corresponding to the tick's year.
set( gca, 'XTick', 1960:1970 );
Here is the output plot.
Doing 1 year intervals get VERY MESSY with lots of data. So solutions include doing a larger interval or setting your ticks to display vertically instead of horizontally. This code below shows how to set 5 year intervals instead.
set( gca, 'XTick', 1960:5:2010 );

Related

Plotting a set of data with time in hh:mm format in x axis in matlab

I have a code which goes like this:
clc;clear;close all
%%
Time=linspace(16.8,17.8,230400)';
Field=linspace(50,145,230400)';
figure('units','normalized','outerposition',[0 0 1 1])
plot(Time,Field)
%%
figure('units','normalized','outerposition',[0 0 1 1])
hammng_wndw_size=4096;
window=hamming(hammng_wndw_size); %window size
noverlap=512; % the noverlaps its the no. of points for repeating the window
nfft=4096; %size of fft
fs=32; %sampling freq
[Sp,F,T,P]=spectrogram(Field,window,noverlap,nfft,fs,'yaxis');
T_forspectrogrm=T./3600+Time(1);
surf(T_forspectrogrm,F,10*log10(P),'edgecolor','none','FaceColor','interp');
axis tight;ylim([0 4]);view(0,90);
colormap(jet);colorbar;
The result of this plot is these two figures:
The xaxis is time and y axis is some other quantity, lets say field. Now, when I plotting, the x axis starts from 16.8 to 17.8 for first figure and 16.8 and 18.8 for second figure. This actually corresponds to 16:48:00 to 17:48:00 and similarly for the second one. How do I have to modify the program to convert the x-axis into hh:mm format do this job?
I tried in this fashion
TimeInReqFrmat=datestr(Time(:,1),'HH:MM:SS'), but this gives me a string of characters.
I am using Matlab 2016a.
Thanks in advance
You approach was almost right. You need to use datetimes. It's just a bit tricky to convert decimal numbers to date times
x = [16.8;17.8]
H = floor(x); % hour
m = floor((x-H)*60); % minute
S = (x-H)*60-m; % second
% create date vector
DateVec = datetime(0,0,0,H,m,S);
plot(DateVec,rand(size(DateVec)))
% set the tick format
xtickformat('HH:mm')
There are many options to set the xtickformat.
If you have unix-time, you can convert it right away
datetime(x,'ConvertFrom','datenum')
If you have just time, you will need to come up with a date for a proper datetime. Otherwiese you can also think of using duration.

Repeat values in x-axis matlab

I'm trying to create a plot about crimes in my city per 100000 inhabitants (the plot 1 above), x-axis is the year of the crime and y-axis the crime per 100000 inhabitants. I've a problem with x-axis because it repeat the years. How can i avoid it? I want to each year only show up a time.
Code:
data = xlsread('Pico.xls');
x = [2012 2013 2014 2015 2016];
plot( x,data(2,:),'-C',x, data(3,:),'-V',x, data(4,:),'-V',x, data(5,:),'-V')
xtickformat('%i')
You want the x-axis ticks equal to the values in your x variable. To achieve that, add this after your code:
set(gca, 'xtick', x)

Using datetick to label x axis: but don't show the last tick label

Does anyone know how to remove the last ticklabel on a plot in Matlab AFTER using the datetick function to put the labels there?
I am plotting Y data and X dates (years and months converted to a datenum).
Then I am using the following to plot the year labels on the xaxis:
close all;clear all;clc;
[num,txt,raw] = xlsread('data.xlsx');
yr = num(:,1);
mth= num(:,2);
data= num(:,3);
dates=datenum(yr,mth,1);
plot(dates,data,'r-.','linewidth',2);
dateFormat = 10;
datetick('x',dateFormat)
I would like to remove the last tick label, as it is including a year that isn't in the datset (presumably Matlab is optimising the distance between ticks and interpolating to the next year).
You should set the ticks you want on your chart first, e.g.:
set(gca, 'XTick', x_values_you_want_ticks_at);
Then use datetick with 'keepticks' option, which will preserve your ticks location:
datetick(gca, 'x', dateFormat, 'keepticks');

MATLAB Plotting a monthly data on a daily axis

I have a plot that has 528 points on the x-axis. The x-axis is labelled by mmm yyyy. I want to plot data over it, but the data is in monthly form. I want to take each of the monthly data points and plot it at the beginning of the month as a dot.
% Axis and plot
t = 731:1258; % 20120101 to 20130611
y = reshape(dataPoint_Anom1x1(:,:,731:end),[],1); % Size 528x1
x = datenum(2009, 12, 31) + t; % Convert t into serial numbers
plot(x, y); % Plot data
hold on
The part below is what I'm having trouble with. The dataPoint_Clim1x1 is size 12x1. (1,1) corresponds to January, (2,1) corresponds to February, etc. I need to plot the corresponding month's climatology point as a dot at the beginning of each month between January 2012 and June 2013.
%%%% Plot climatology on the same graph
dataClim_1x1 = dataClim(u,v,:); % Array that only contains points 1 degree away from 72.5E and 67.25S
B = mean(dataClim_1x1); % Average along the column
dataPoint_Clim1x1 = mean(B,2); % Average along the row
x_dataClim = ???
y_dataClim = reshape(dataPoint_Clim1x1, [],1); % Change dataPoint_Clim1x1 into a 1 column matrix
plot(x_dataClim,y_dataClim) % y_dataClim is only 12x1.
So the plot command right above is wrong. Do I just need to somehow set up the x-axis so that it plots every month with datenum somehow? I don't want to use a secondary axis though.
I think you just need to define your x coordinates of the points with
x_dataClim = datenum(2011, 1:12, 1);
This generates "the first of the month":
>> datestr(x_dataClim)
ans =
01-Jan-2011
01-Feb-2011
01-Mar-2011
01-Apr-2011
01-May-2011
01-Jun-2011
01-Jul-2011
01-Aug-2011
01-Sep-2011
01-Oct-2011
01-Nov-2011
01-Dec-2011
The cool thing is that you can actually "go into next year" - so
>> datestr(datenum(2011, 11:14, 1))
ans =
01-Nov-2011
01-Dec-2011
01-Jan-2012
01-Feb-2012
Here's what I ended up doing:
x = datenum(2011,1:30,1); % 30 months of data (2 and 1/2 years)
y_dataClim = reshape(dataPoint_Clim1x1, [],1); % Change dataPoint_Clim1x1 into a 1 column matrix
y = cat(1, y_dataClim, y_dataClim, y_dataClim(1:6,:));
scatter(x,y, 50,'fill'); % Plot scatter plot

Merge two (or more) time stamped data and plot showing the gap(s)

what is the best way to merge and plot 2 (or more) time stamped data so that the plot includes the gaps between the known data?
For example, I have a cell with time and heart rate values for Monday, and another for Friday. I would like to plot all data from Mon to Friday which includesthe gaps showing nothing was recorded from Tues-Thurs?
So far if I merge the data
data = [mon;fri]
% get the time serial numbers
dateInd = 1;
dateString = data(dateIndex);
dateFormat = 'dd/mm/yyyy HH:MM:SS';
tNum = datenum(dateString{1},dateFormat);
t = linspace(tNum(1),tNum(end),length(tNum));
% get heart rates,
HRIndex = 2;
HR = data(HRIndex);
and plot
plot(t,HR)
datetick('x','ddd');
I obviously get Monday and Fridays data merged into a single plot 2 days long. but I would like to have a plot 5 days long with data only showing on monday and Friday. What is the best way to achieve this?
I hope this makes sense,
Many thanks,
Jon
To achieve such effect I usually fill missing data with NaNs, like here:
x = linspace(0,2*pi,100);
y = sin(x);
y(20:30) = NaN; % there will be a gap from point#20 to point#30
plot(x,y);
The reason is that MatLab does not draw plot points where either x or y data are NaNs.
In your case you may add missing time points to your time data (to have corect gap) and NaNs to corresponding Y-values.
By the way, why don't you plot two separate plots with X-data of the second one properly shifted?
EDIT
Case 1: your x-data is time relative to the start of the day (in 0-24 interval). If you plot them directly they will overlap. You have to add some offset manually, like this:
% generate test data
x1 = linspace(0,1,25); % 25 points per first day
y1 = rand(25,1);
x2 = linspace(0,1,25); % 25 points per second day
y2 = rand(25,1);
% plot them as two separate plots
% so line style, color, markers may be set separately
XOffset = 3;
figure;
plot(x1,y1,'*k-', x2+XOffset,y2,'*r-');
% plot them as single separate plot
% so line style, color, markers are the same
figure;
plot([x1(:); NaN; x2(:)+XOffset],[y1(:); NaN; y2(:)],'*k-');
% One NaN is enough to insert a gap.
Case 2: your x-data have full time information including the date (like MatLab's serial date number, see help on now function, for example). Then just plot them, they will be offset automatically.
% generate test data
XOffset = 3;
x1 = linspace(0,1,25); % 25 points per first day
y1 = rand(25,1);
x2 = linspace(0,1,25)+XOffset; % 25 points per second day, with offset
y2 = rand(25,1);
% plot them as two separate plots
% so line style, color, markers may be set separately
figure;
plot(x1,y1,'*k-', x2,y2,'*r-');
% plot them as single separate plot
% so line style, color, markers are the same
figure;
plot([x1(:); NaN; x2(:)],[y1(:); NaN; y2(:)],'*k-');
% One NaN is enough to insert a gap.
Also instead of
plot(x1,y1,'*k-', x2,y2,'*r-');
you may do like this (number of plots is not limited):
hold on;
plot(x1,y1,'*k-');
plot(x2,y2,'*r-');
hold off;