Black Lives Matter. Please consider donating to Black Girls Code today.
https://www.blackgirlscode.com/

Time Series in MATLAB®

How to plot date and time in MATLAB®. An example of a time-series plot.


Converting time series plots from MATLAB® to plotly requires a few extra steps. Since MATLAB® is extremely flexible with how the dates can be formatted within the X and Y tick labels, automatically parsing the various permutations of the date labels is nearly impossible. Here are two options for plotting time series in MATLAB® with Plotly.

Converting to a Standard Date Format

The first way to convert MATLAB® time series plots is to convert the dates to unix time with the convertDate function included in Plotly Graphing Library for MATLAB®.
  1. Convert your MATLAB® time values to the "milliseconds from 1969" time format with convertDate below.
  2. Run >> plotlyfig = fig2plotly(gcf) to parse your figure.
  3. Modify the converted figure's date axes: plotlyfig.layout.xaxis1.type = 'date';
    Note: the xaxis1 might be xaxisN—> depending on the number of axes you have, where N is the id of the axis you wish to modify.
  4. Change the file option to overwrite your newly created plot:
    >> plotlyfig.PlotOptions.FileOpt = 'overwrite';
  5. Send your figure back to Plotly:
    >> plotly(plotlyfig);
Example
x = linspace(datenum(2009,01,01),datenum(2010,01,01),12);
y = rand(1,12);
plotlydate = convertDate(x);
plot(plotlydate,y);
plotlyfig = fig2plotly(gcf,'filename','myfig');
plotlyfig.layout.xaxis1.type = 'date';
plotlyfig.PlotOptions.FileOpt = 'overwrite';
plotly(plotlyfig);

Explicitly Setting the Date Format

A second way to convert MATLAB® time series plots to Plotly is by explicitly setting the date-time format.
  1. set the date-string format, for example: userdata.plotly.xdateformat = ‘yyyy:mm:hh’;
  2. set(your_axis_handle, ‘UserData’, userdata)
  3. Send your figure to plotly: plotlyfig = fig2plotly(gcf);
Example
startDate = datenum('01-01-2009');
endDate = datenum('12-31-2009');
xData = linspace(startDate,endDate,12);
plot(xData,rand(1,12))
set(gca,'XTick',xData)
dateformat = 'yy:mmm';
datetick('x',dateformat,'keepticks')
userdata.plotly.xdateformat = dateformat;
set(gca,'UserData',userdata)
p = fig2plotly(gcf);
% Learn about API authentication here: https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

data = {...
  struct(...
    'x', { {'2013-10-04 22:23:00', '2013-11-04 22:23:00', '2013-12-04 22:23:00'} }, ...
    'y', [1, 3, 6], ...
    'type', 'scatter')...
};
response = plotly(data, struct('filename', 'date-axes', 'fileopt', 'overwrite'));
plot_url = response.url

MATLAB is a registered trademark of The MathWorks, Inc.