Plot Dates and Durations

You can create plots of datetime and duration values with a variety of graphics functions. You also can customize the axes, such as changing the format of the tick labels or changing the axis limits.

Line Plot with Dates

Create a line plot with datetime values on the x-axis. Then, change the format of the tick labels and the x-axis limits.

Create t as a sequence of dates and create y as random data. Plot the vectors using the plot function.

t = datetime(2014,6,28) + calweeks(0:9);
y = rand(1,10);
plot(t,y);

By default, plot chooses tick mark locations based on the range of data. When you zoom in and out of a plot, the tick labels automatically adjust to the new axis limits.

Change the x-axis limits. Also, change the format for the tick labels along the x-axis. For a list of formatting options, see the xtickformat function.

xlim(datetime(2014,[7 8],[12 23]))
xtickformat('dd-MMM-yyyy')

Line Plot with Durations

Create a line plot with duration values on the x-axis. Then, change the format of the tick labels and the x-axis limits.

Create t as seven linearly spaced duration values between 0 and 3 minutes. Create y as a vector of random data. Plot the data.

t = 0:seconds(30):minutes(3);
y = rand(1,7);
plot(t,y);

View the x-axis limits. Since the duration tick labels are in terms of a single unit (minutes), the limits are stored in terms of that unit.

xl = xlim
xl = 1x2 duration
    -4.5 sec   184.5 sec

Change the format for the duration tick labels to display in the form of a digital timer that includes more than one unit. For a list of formatting options, see the xtickformat function.

xtickformat('mm:ss')

View the x-axis limits again. Since the duration tick labels are now in terms of multiple units, the limits are stored in units of 24-hour days.

xl = xlim
xl = 1x2 duration
   -00:04    03:04

Scatter Plot with Dates and Durations

Create a scatter plot with datetime or duration inputs using the scatter or scatter3 functions. For example, create a scatter plot with dates along the x-axis.

t = datetime('today') + caldays(1:100);
y = linspace(10,40,100) + 10*rand(1,100);
scatter(t,y)

Plots that Support Dates and Durations

You can create other types of plots with datetime or duration values. These graphics functions support datetime and duration values.

barbarh
plotplot3
semilogx (x values must be numeric)semilogy (y values must be numeric)
stemstairs
scatterscatter3
areamesh
surfsurface
fillfill3
linetext
histogram 

See Also

| |