Main Content

Plot Dates and Times

This example shows how to create line plots with dates and times that are stored as datetime and duration arrays. The datetime data type represents points in time, such as August 24, 2020, 10:50:30 a.m., while the duration data type represents lengths of time, such as 12 hours and 30 minutes. Most plotting functions accept datetime and duration arrays as x-, y-, and z-coordinates and show tick values with appropriate date and time units. You can specify your own axis limits and tick values using datetime and duration values. You can also change the format of tick values to show date and time units of your choice. Data tips show datetime and duration values for cursor positions on a plot, and you can export those values to workspace variables. When you read data from a spreadsheet or comma-separated value (CSV) file, you can include the date and time data in your plots.

Plot Date and Time Data

You can plot datetime and duration arrays without converting them to numeric arrays. Most plotting functions accept datetime and duration arrays as input arguments.

For example, plot a data set that has datetime values on the x-axis and numeric values on the y-axis. The x-coordinates are the datetime values for every day in June and July 2021. The plot automatically displays tick values with an appropriate format on the x-axis. In this case, the appropriate format shows month names and day numbers with the year.

XDates = [datetime(2021,6,1:30) datetime(2021,7,1:31)];
YNumsForXDates = sin(0:0.1:6);
plot(XDates,YNumsForXDates)

Figure contains an axes object. The axes object contains an object of type line.

Similarly, plot a data set that has duration values on the x-axis. To create a duration array in units of seconds, use the seconds function.

XTimes = seconds(0:120);
YNumsForXTimes = cos(0:0.05:6);
plot(XTimes,YNumsForXTimes)

Figure contains an axes object. The axes object contains an object of type line.

Specify Axes Limits

When you change the limits on a plot, the tick values that are shown for datetime and duration values are updated automatically. You can update limits interactively or by calling the xlim, ylim, or zlim functions for the corresponding axis. Specify the new limits as a datetime or duration array. If you change limits to zoom in or zoom out far enough, then the tick values can show other date and time components, not just new tick values.

For example, plot the XDates and YNumsForXDates arrays. Then change the x-axis limits to June 20 and July 7, 2021, using xlim. The plot displays new tick values.

plot(XDates,YNumsForXDates)
xlim([datetime("2021-06-20") datetime("2021-07-07")])

Figure contains an axes object. The axes object contains an object of type line.

Change the x-axis limits to June 20 and June 22, 2021. The tick values show hour and minute components in hh:mm format because the plot is zoomed in enough to show smaller time units on the x-axis.

xlim([datetime("2021-06-20") datetime("2021-06-22")])

Figure contains an axes object. The axes object contains an object of type line.

Specify Tick Values

You do not have to change axes limits to change tick values. Instead, you can specify your own tick values along the x-, y-, or z-axes by using the xticks, yticks, or zticks functions. Specify the tick values as a datetime or duration array.

For example, plot the XTimes and YNumsForXTimes arrays. Then specify tick values at 0, 60, and 120 seconds by using xticks.

plot(XTimes,YNumsForXTimes)
xticks(seconds([0 60 120]))

Figure contains an axes object. The axes object contains an object of type line.

Specify Tick Format

Plotting functions use default formats to display datetime and duration values as tick values. To override the format for the tick values on an axis, use the xtickformat, ytickformat, or ztickformat functions.

For example, plot XDates and YNumsForXDates. Specify a tick value format showing year, month, and day numbers by using xtickformat.

plot(XDates,YNumsForXDates)
xtickformat("yyyy-MM-dd")

Figure contains an axes object. The axes object contains an object of type line.

As an alternative, you can also call plot with the DatetimeTickFormat or DurationTickFormat name-value arguments. For example, this call to the plot function creates the same plot.

plot(XDates,YNumsForXDates,"DatetimeTickFormat","yyyy-MM-dd")

However, these name-value arguments can be used with the plot function only. You can use functions such as xtickformat after calling any plotting function, such as scatter, stem, and stairs.

Axes Properties That Store Dates and Times

Axis limits, the locations of tick labels, and the x-, y-, and z-values for datetime and duration arrays in line plots are also stored as properties of an Axes object. These properties represent those aspects of line plots.

  • XLim, YLim, ZLim

  • XTick, YTick, ZTick

  • XData, YData, ZData

For example, the XLim and XTick properties associated with the plot of XDates and YNumsForXDates store datetime values. Get the Axes object for the plot and display these properties.

ax = gca;
ax.XLim
ans = 1x2 datetime
   2021-06-01   2021-08-03

ax.XTick
ans = 1x5 datetime
   2021-06-01   2021-06-15   2021-06-29   2021-07-13   2021-07-27

Export and Convert Data Tip Values

When you click on a plot, you create a data tip at that cursor position that displays its x- and y-coordinates. Data tips display numeric values as well as datetime and duration values. However, when you export the cursor data to the workspace, the coordinates are reported as a pair of numeric values. To convert exported cursor data to the datetime or duration value, use the num2ruler function.

For example, plot XDates and YNumsForXDates. Then create a data tip by clicking on the plot.

DatetimeDataTip.png

To export the cursor data to the workspace, right-click the data tip and select Export Cursor Data to Workspace. This action exports the cursor data to a structure in the workspace.

cursor_info = 

  struct with fields:

       Target: [1×1 Line]
     Position: [25 0.5985]
    DataIndex: 26

The cursor_info.Position field represents the cursor data as a pair of numeric values. The Axes object associated with the plot has the information needed to convert the numeric value of the x-coordinate to a datetime value. Get the Axes object for the plot. Then pass the numeric x-coordinate and the x-axis from the Axes object to num2ruler.

ax = gca;
datetimePosition = num2ruler(cursor_info.Position(1),ax.XAxis)

datetimePosition = 

  datetime

   26-Jun-2021

You do not need to convert the numeric y-coordinate, cursor_info.Position(2) because the y-values in this plot are numeric.

Plot Dates and Times from File

Data files such as spreadsheets and CSV files often store dates and times as formatted text. When you read in data from such files, you can convert text representing dates and times to datetime or duration arrays. Then you can create plots of that data.

For example, create a plot of data from the example data file outages.csv. This CSV file contains six columns of data. Two columns contain text that represent dates and times.

Region,OutageTime,Loss,Customers,RestorationTime,Cause
SouthWest,2002-02-01 12:18,458.9772218,1820159.482,2002-02-07 16:50,winter storm
SouthEast,2003-01-23 00:49,530.1399497,212035.3001,,winter storm
SouthEast,2003-02-07 21:15,289.4035493,142938.6282,2003-02-17 08:14,winter storm
...

The recommended way to read data from a CSV file is to use the readtable function. This function reads data from a file and returns it in a table.

Read in outages.csv. The readtable function automatically converts the text in the OutageTime and RestorationTime columns to datetime arrays. The columns that represent numbers (Loss and Customers) are read in as numeric arrays. The remaining columns are read in as strings. The table stores the columns of data from outages.csv in table variables that have the same names. Finally, sort the rows of T by the dates and times in OutageTime by using the sortrows function. If a table is not sorted by time, then it is a best practice to sort the table by time before plotting or analyzing the data.

T = readtable("outages.csv","TextType","string");
T = sortrows(T,"OutageTime")
T=1468×6 table
      Region            OutageTime          Loss     Customers       RestorationTime             Cause       
    ___________    ____________________    ______    __________    ____________________    __________________

    "SouthWest"    01-Feb-2002 12:18:00    458.98    1.8202e+06    07-Feb-2002 16:50:00    "winter storm"    
    "MidWest"      05-Mar-2002 17:53:00    96.563    2.8666e+05    10-Mar-2002 14:41:00    "wind"            
    "MidWest"      16-Mar-2002 06:18:00    186.44    2.1275e+05    18-Mar-2002 23:23:00    "severe storm"    
    "MidWest"      26-Mar-2002 01:59:00    388.04    5.6422e+05    28-Mar-2002 19:55:00    "winter storm"    
    "MidWest"      20-Apr-2002 16:46:00     23141           NaN                     NaT    "unknown"         
    "SouthWest"    08-May-2002 20:34:00    50.732         34481    08-May-2002 22:21:00    "thunder storm"   
    "MidWest"      18-May-2002 11:04:00    1389.1    1.3447e+05    21-May-2002 01:22:00    "unknown"         
    "NorthEast"    20-May-2002 10:57:00    9116.6    2.4983e+06    21-May-2002 15:22:00    "unknown"         
    "SouthEast"    27-May-2002 09:44:00    237.28    1.7101e+05    27-May-2002 16:19:00    "wind"            
    "SouthEast"    02-Jun-2002 16:11:00         0             0    05-Jun-2002 05:55:00    "energy emergency"
    "West"         06-Jun-2002 19:28:00    311.86           NaN    07-Jun-2002 00:51:00    "equipment fault" 
    "SouthEast"    17-Jun-2002 23:01:00    42.542         39877    17-Jun-2002 23:49:00    "thunder storm"   
    "MidWest"      01-Jul-2002 04:33:00    203.94         60650    02-Jul-2002 14:54:00    "severe storm"    
    "MidWest"      01-Jul-2002 08:18:00    100.71    1.8116e+05    01-Jul-2002 11:33:00    "severe storm"    
    "MidWest"      10-Jul-2002 01:49:00    168.02           NaN    10-Jul-2002 17:20:00    "equipment fault" 
    "SouthEast"    14-Jul-2002 21:32:00     90.83         60133    14-Jul-2002 23:53:00    "thunder storm"   
      ⋮

You can access table variables by using dot notation, referring to a table variable by name. With dot notation, you can treat table variables like arrays.

Plot the power loss against outage time. To access these variables from the table, use dot notation.

plot(T.OutageTime,T.Loss)

Figure contains an axes object. The axes object contains an object of type line.

Calculate the durations of the power outages and plot them against OutageTime. To calculate the durations, subtract OutageTime from RestorationTime. The result, OutageDuration, is a duration array, because arithmetic with datetime values produces lengths of time as output. Some of these outage durations are long, so change the format of the y-axis tick values from hours to years by using ytickformat. The fact that some outages apparently last for years indicates there might be a few questionable data values in the file. Depending on how you plan to analyze the data, you can either reprocess it in some way or remove the rows containing bad values.

OutageDuration = T.RestorationTime - T.OutageTime;
plot(T.OutageTime,OutageDuration)
ytickformat("y")

Figure contains an axes object. The axes object contains an object of type line.

See Also

| | | | | | | |

Related Topics