Kahibaro
Discord Login Register

17.4 Plotting Data over Time

Time based plotting in MATLAB

When your data includes dates and times, simple line plots are often not enough. MATLAB provides specialized support for plotting time based data so that the horizontal axis shows meaningful date or time labels instead of plain numbers. This chapter focuses on how to use those features once you already have your data in one of MATLAB’s time related types, such as datetime or duration.

Using datetime on the x axis

The most common situation is that you have measurements taken at specific clock times, and you want those times on the horizontal axis. If your time information is stored in a datetime array, you can pass it directly to plotting functions such as plot, scatter, or stairs.

For a simple line plot, you can write:

t = datetime(2025,1,1,0,0,0) + minutes(0:10:120);
y = rand(size(t));
plot(t, y)

MATLAB automatically detects that t is a time based type and sets up the axis ticks and labels using calendar dates and clock times instead of raw numeric values. You do not need any special plotting function for this; the regular plot supports time arrays.

If you only provide a single datetime vector to plot, MATLAB treats it as the vertical data and uses its index as the horizontal coordinate. To avoid this, always pass both the time values and the dependent values, in the form plot(time, data).

Using duration and calendarDuration

Sometimes your horizontal axis should represent elapsed time instead of calendar date and clock time. For example, you may want to measure seconds or hours since the start of an experiment, without caring about the actual date. In that case, you can use duration arrays.

The plotting approach is the same as with datetime:

t = seconds(0:0.5:10);
signal = sin(2*pi*0.5*t);
plot(t, signal)

The horizontal axis now has tick labels such as 0 sec, 2 sec, and so on. For longer periods, such as days or months, you can use hours, days, or create a duration explicitly.

If your time spacing is irregular and measured in combinations such as years, months, and days, you may encounter calendarDuration. These also work on the horizontal axis. The key point is that all these time related types can be used directly in standard plotting functions.

Controlling time axis limits and zoom

You can restrict the visible time span of a plot using xlim with datetime or duration values. You do not need to convert to numbers. For example:

startTime = datetime(2025,1,1,1,0,0);
endTime   = datetime(2025,1,1,3,0,0);
xlim([startTime endTime])

MATLAB will clip the displayed data to that time interval and adjust the tick marks accordingly. This is often useful with large time series when you want to focus on a particular window.

When you zoom or pan interactively using the toolbar on a time based plot, the axis continues to show valid date or duration labels in the new range. You can combine xlim with commands like ylim for vertical limits in the usual way, since the vertical axis is usually numeric.

Formatting date and time tick labels

By default, MATLAB chooses a label style for the time axis based on the range you are viewing. For example, if the plot covers only a few hours, you may see tick labels containing only times such as 14:00. If the plot covers several days, labels may include the date.

You can customize this using properties of the axis. The relevant properties are XTickLabelRotation for rotation and, more importantly, TickLabelFormat for the format of the time values. To modify them, first get the current axes handle with gca:

ax = gca;
ax.XAxis.TickLabelFormat = 'HH:mm';

In this example, the tick labels on the horizontal axis will show only hours and minutes, such as 10:30. You can use other format strings to include dates, seconds, or combinations, such as 'dd-MMM-yyyy HH:mm'.

If you want to emphasize the date and hide the time, you could use a format such as 'dd-MMM-yyyy'. MATLAB interprets the format string according to the rules for datetime display formats, so you can reuse formats you have already seen when working with datetime arrays.

Rotation of the labels can help when dates are long:

ax.XTickLabelRotation = 45;

This tilts the labels, which can make them more readable when they contain both date and time information.

Using timetable for time series plots

When your data is stored as a timetable, plotting becomes more convenient because the row times are built into the data structure. A common pattern is to create a timetable where the row times are datetime values and each column is a variable such as temperature, pressure, or signal amplitude.

To plot one variable from a timetable, you can use dot indexing and pass it to plot together with the time index:

% Assume tt is a timetable with row times and a variable named Temperature
plot(tt.Time, tt.Temperature)

Alternatively, some plotting functions can accept the timetable directly and infer the horizontal coordinate from its row times. For example:

plot(tt.Time, tt{:,'Temperature'})

or, with multiple variables:

plot(tt.Time, tt{:, {'Temperature','Pressure'}})

Each selected variable appears as a separate line on the same time axis. The legend entries use the variable names from the timetable, so careful naming makes the plot clearer.

Because timetable remembers the time information, it is particularly suited for sequences whose samples are taken at known times but possibly irregular intervals. All the axis control and formatting techniques that work with datetime also apply when the times come from a timetable.

Plotting multiple time series together

It is very common to compare two or more time based variables that share the same time axis. If the time values come from the same datetime or duration array, you can plot them together by passing a matrix of vertical data to plot:

plot(t, [y1 y2 y3])

In this case, each column in the vertical data matrix becomes a separate line. You can then add a legend to distinguish them.

If your series have different time vectors, you have two main options. You can resample them onto a common time base before plotting, or you can call hold on and plot each series separately:

plot(t1, y1)
hold on
plot(t2, y2)
hold off

Both approaches still give you meaningful date and time labels, but you must make sure you interpret misaligned times correctly. If the series are converted into a single timetable with a shared set of row times, plotting from the timetable can help you avoid mismatched data.

Handling different time scales and ranges

Sometimes you need to plot data that covers very different time scales, for example seconds within a single day, or daily values over several years. MATLAB adjusts the tick spacing automatically based on the total range of the time axis, but you may need to choose a display format that matches the scale that you care about.

If you are inspecting a narrow part of a long series, you can zoom into that section either interactively or by setting limits. After zooming, the format for tick labels may change automatically to emphasize hours and minutes instead of dates. You can override this with TickLabelFormat if you want to keep consistent labels while moving around the data.

For long term plots such as monthly averages over several years, consider making the time values represent the first day of each month or a similar convention. This produces clear date labels like Jan 2025 instead of ambiguous mid month positions.

If you need to present both the date and an index based axis, you usually create two separate plots, or you use a secondary axis. The secondary axis still uses numeric values, so you should be clear which axis is which. However, for most time based work, keeping the true time axis as your primary horizontal axis is the safest and clearest choice.

Annotating time based plots

When marking events or intervals on a time plot, you can use the same functions that you would use for numeric plots, but provide times as datetime or duration. For example, to add a vertical line at a specific time, you can draw a simple line using xline:

eventTime = datetime(2025,1,1,2,0,0);
xline(eventTime, 'r--', 'Event')

This draws a vertical red dashed line at that time and labels it. You can also highlight periods using area or shaded patches where the horizontal coordinates are time values. The important idea is that these helper functions also accept datetime and duration where numeric values are normally used.

To label particular data points, you can use text with time coordinates:

text(eventTime, yValue, 'Peak')

MATLAB places the label at the specified time and vertical value in the coordinate system of the plot.

Exporting and sharing time based figures

Once you have created a time based plot, you can save it to a file in the same ways as any other figure. The time axis and its labels are stored as part of the figure object, so you will see the same date and time representation when you reopen or export the figure.

For export, it is often useful to check that the tick label format is clear and not overly detailed, because dense time labels can become illegible in small images or printed documents. Adjusting the label format or rotation before exporting can make the final result much easier to read.

You can use commands such as saveas or the export options in the figure window. The underlying data remains in datetime or duration inside MATLAB, so you can always refine the plot later without changing how the time values are stored.

Key points: Use datetime or duration values directly on the horizontal axis when plotting time based data. Control the visible time range with xlim using time values, and customize tick labels with the axis TickLabelFormat property. When working with timetable, use its row times and variable names to create clear, time aware plots, and always pass both time and data to plotting functions to avoid unintended indexing on the horizontal axis.

Views: 85

Comments

Please login to add a comment.

Don't have an account? Register now!