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