17.4. Plotting Data over Time
Table of Contents
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: 0
Where to Move
Move chapter:
- ☰ 1. Getting Started with MATLAB
- ☰ 1.1. What Is MATLAB and What Is It Used For
- ☰ 1.2. Installing MATLAB and Setting Up the Environment
- ☰ 1.3. Understanding the MATLAB Desktop Interface
- ☰ 1.4. Command Window, Workspace, and Current Folder
- ☰ 1.5. Basic Workflow and Running Simple Commands
- ☰ 1.6. Getting Help and Documentation
-
- ☰ 2. MATLAB Language Basics
- ☰ 2.1. MATLAB Syntax and Expressions
- ☰ 2.2. Variables and Assignment
- ☰ 2.3. Data Types and Type Conversion
- ☰ 2.4. Vectors and Matrices Fundamentals
- ☰ 2.5. Creating and Indexing Arrays
- ☰ 2.6. Basic Arithmetic and Elementwise Operations
- ☰ 2.7. Using Built-In Constants and Functions
-
- ☰ 3. Working with Variables and the Workspace
- ☰ 3.1. Creating, Viewing, and Editing Variables
- ☰ 3.2. Workspace Browser and Variable Inspector
- ☰ 3.3. Saving and Loading Data Files
- ☰ 3.4. MAT-Files and Importing External Data
- ☰ 3.5. Clearing Variables and Managing the Workspace
-
- ☰ 4. Vectors, Matrices, and Arrays
- ☰ 4.1. Row and Column Vectors
- ☰ 4.2. Matrix Creation and Concatenation
- ☰ 4.3. Indexing, Slicing, and Logical Indexing
- ☰ 4.4. Matrix Operations vs Elementwise Operations
- ☰ 4.5. Reshaping and Rearranging Arrays
- ☰ 4.6. Special Matrices and Functions
-
- ☰ 5. Basic Programming Constructs
- ☰ 5.1. Scripts vs Functions
- ☰ 5.2. Control Flow with if, elseif, else
- ☰ 5.3. Loops with for and while
- ☰ 5.4. break, continue, and return
- ☰ 5.5. Logical Expressions and Relational Operators
- ☰ 5.6. Best Practices for Clear and Readable Code
-
- ☰ 6. Functions in MATLAB
- ☰ 6.1. Creating Simple Functions
- ☰ 6.2. Function Inputs and Outputs
- ☰ 6.3. Function Files and the Path
- ☰ 6.4. Local vs Global Variables
- ☰ 6.5. Anonymous Functions
- ☰ 6.6. Organizing Code into Multiple Functions
-
- ☰ 7. Working with Numbers and Math
- ☰ 7.1. Scalars and Vectorized Computations
- ☰ 7.2. Basic Mathematical Functions
- ☰ 7.3. Trigonometric and Exponential Functions
- ☰ 7.4. Complex Numbers in MATLAB
- ☰ 7.5. Rounding, Modulo, and Special Values
- ☰ 7.6. Numerical Precision and Floating Point Considerations
-
- ☰ 8. Strings, Characters, and Categorical Data
- ☰ 8.1. Character Arrays and String Arrays
- ☰ 8.2. Creating and Manipulating Strings
- ☰ 8.3. Converting Between Data Types and Strings
- ☰ 8.4. Comparing and Searching Strings
- ☰ 8.5. Categorical Arrays Basics
-
- ☰ 9. Tables, Structures, and Cell Arrays
- ☰ 9.1. Introduction to Tables
- ☰ 9.2. Creating Tables and Accessing Data
- ☰ 9.3. Modifying and Joining Tables
- ☰ 9.4. Structures and Nested Structures
- ☰ 9.5. Cell Arrays and Cell Indexing
- ☰ 9.6. Choosing the Right Container Type
-
- ☰ 10. Importing and Exporting Data
- ☰ 10.1. Reading Text and CSV Files
- ☰ 10.2. Importing Excel Spreadsheets
- ☰ 10.3. Importing Data with the Import Tool
- ☰ 10.4. Exporting Data to Files
- ☰ 10.5. Working with Image and Audio Files
- ☰ 10.6. Basic File Management from MATLAB
-
- ☰ 11. Plotting and Visualization
- ☰ 11.1. Introduction to 2D Plotting
- ☰ 11.2. Customizing Plots and Axes
- ☰ 11.3. Multiple Plots in One Figure
- ☰ 11.4. Labels, Titles, Legends, and Annotations
- ☰ 11.5. Plotting with Different Line and Marker Styles
- ☰ 11.6. Saving and Exporting Figures
-
- ☰ 12. Advanced Plotting for Beginners
- ☰ 12.1. Subplots and Tiled Layouts
- ☰ 12.2. Bar, Scatter, and Stem Plots
- ☰ 12.3. Histograms and Density Plots
- ☰ 12.4. 3D Plots and Surface Plots
- ☰ 12.5. Using plottools and Interactive Editing
- ☰ 12.6. Basics of Handle Graphics
-
- ☰ 13. Working with Scripts and Live Scripts
- ☰ 13.1. Creating and Running Script Files
- ☰ 13.2. Sectioning Code and Running Sections
- ☰ 13.3. Live Scripts and Rich Text
- ☰ 13.4. Adding Equations, Images, and Outputs
- ☰ 13.5. Sharing and Exporting Live Scripts
-
- ☰ 14. Debugging and Code Quality
- ☰ 14.1. Finding and Fixing Syntax Errors
- ☰ 14.2. Setting Breakpoints and Stepping Through Code
- ☰ 14.3. Inspecting Variable Values During Execution
- ☰ 14.4. Using the Editor Debugging Tools
- ☰ 14.5. Using Code Analyzer and Warnings
- ☰ 14.6. Writing Clean and Maintainable MATLAB Code
-
- ☰ 15. Basic Linear Algebra with MATLAB
- ☰ 15.1. Vectors and Norms
- ☰ 15.2. Matrix Addition and Multiplication
- ☰ 15.3. Solving Linear Systems with Backslash
- ☰ 15.4. Inverses, Determinants, and Rank
- ☰ 15.5. Eigenvalues and Eigenvectors
- ☰ 15.6. Using Linear Algebra Functions Safely
-
- ☰ 16. Data Analysis and Statistics Fundamentals
- ☰ 16.1. Descriptive Statistics and Summary Measures
- ☰ 16.2. Sorting, Filtering, and Grouping Data
- ☰ 16.3. Basic Correlation and Regression
- ☰ 16.4. Simple Data Cleaning Techniques
- ☰ 16.5. Basic Time Series Handling
-
- ☰ 17. Working with Time and Dates
- ☰ 17.1. Representing Dates and Times
- ☰ 17.2. Creating and Formatting datetime Arrays
- ☰ 17.3. Date Calculations and Differences
- ☰ 17.4. Plotting Data over Time
-
- ☰ 18. Introduction to Signal and Image Handling
- ☰ 18.1. Basic Signal Representation in MATLAB
- ☰ 18.2. Simple Filtering and Transformations
- ☰ 18.3. Reading, Displaying, and Writing Images
- ☰ 18.4. Basic Image Transformations
-
- ☰ 19. Automation and Scripting Tasks
- ☰ 19.1. Batch Processing of Files
- ☰ 19.2. Writing Reusable Utility Scripts
- ☰ 19.3. Using Relative Paths and the MATLAB Path
- ☰ 19.4. Simple User Interaction with input and disp
-
- ☰ 20. Introduction to Toolboxes
- ☰ 20.1. What Are Toolboxes and How to Use Them
- ☰ 20.2. Exploring Installed Toolboxes
- ☰ 20.3. Finding Functions in Toolboxes
- ☰ 20.4. Add-Ons and MATLAB File Exchange
-
- ☰ 21. Best Practices and Next Steps
- ☰ 21.1. Organizing Projects and Folders
- ☰ 21.2. Version Control Basics with MATLAB
- ☰ 21.3. Performance Tips for Beginners
- ☰ 21.4. Learning Resources and Documentation Path
- ☰ 21.5. Suggested Practice Projects for Beginners
-
Comments
Please login to add a comment.
Don't have an account? Register now!